I have a list of divs, some have ids and some don't. I want to find all the divs inside a class which ids match id=""
and change the inner text to "no data available"
. Is this possible?
I tried using $("*[id]")
but it didn't work. This is how my list looks.
<div class="main">
<div id="1"></div>
<div id="2"></div>
<div id=""></div>
<div id="4"></div>
<div id=""></div>
<div id=""></div>
<div id="7"></div>
</div>
I have a list of divs, some have ids and some don't. I want to find all the divs inside a class which ids match id=""
and change the inner text to "no data available"
. Is this possible?
I tried using $("*[id]")
but it didn't work. This is how my list looks.
<div class="main">
<div id="1"></div>
<div id="2"></div>
<div id=""></div>
<div id="4"></div>
<div id=""></div>
<div id=""></div>
<div id="7"></div>
</div>
[id]
matches all elements that have an id
attribute. If you want to specify that they have an empty value, you need to use [id='']
.
– Sebastian Simon
Commented
Aug 20, 2018 at 14:01
Apparently some browsers (e.g. Chrome) will take your empty ID and change it from id=""
to just id
. One way to then handle this is to loop through them and check for an empty value:
$("div[id]").each(function(){
if(this.id==='')$(this).html('no data available')
})
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div id="1">1</div>
<div id="2">2</div>
<div id=""></div>
<div id="4">4</div>
<div id=""></div>
<div id=""></div>
<div id="7">7</div>
</div>
You can filter empty id's.
$(".main div").filter(function() {
return !$(this).attr("id");
});
You can just use CSS to target the elements with no value in the attribute. No JavaScript is needed.
div [id] {
background-color: green;
width: 200px;
height: 1.5em;
margin: .5em;
}
div [id=""] {
background-color: red;
}
div [id=""]::after {
content: "no data available"
}
<div class="main">
<div id="1"></div>
<div id="2"></div>
<div id=""></div>
<div id="4"></div>
<div id=""></div>
<div id=""></div>
<div id="7"></div>
</div>
If you really want to do it with JavaScript/jQuery, you can just select the elements and filter out the ones with an id.
$('div[id]').filter((i,e)=>!e.id.length).text('no data available')
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div id="1"></div>
<div id="2"></div>
<div id=""></div>
<div id="4"></div>
<div id=""></div>
<div id=""></div>
<div id="7"></div>
</div>