I have the following markup
<div class = "general">
<a href = "#world"></a>
<div id ="custom"></div>
</div>
How to change id = "custom"
in all <div>
with class="general"
from href
on page using jQuery?
I have the following markup
<div class = "general">
<a href = "#world"></a>
<div id ="custom"></div>
</div>
How to change id = "custom"
in all <div>
with class="general"
from href
on page using jQuery?
You can try this:
$("div.general").each(function() {
$(this).children("div#custom").text($(this).children("a").attr("href"));
});
If I understand you correctly, you want to iterate through all div.general
s, and change the text of each child div#custom
to the href
of the child a
.
See a working example on JSfiddle.
Also, another tip is to avoid using multiple elements with the same id
. In your code you have a <div>
with id="custom"
. You also say that the div.general
appears multiple times — therefore, the id
"custom" will appear multiple times. This is bad practice. I suggest that you change id
to class
.
You need to loop through all div.general and replace the id attribute of div#custom to whatever is there as the anchors href property. The following code will work:
$(".general").each(function(){
$(this).find("#custom").attr("id", $(this).find("a").attr("href").replace("#", ""));
})
Here the .find() will dig out elements from any depth inside the parent. If you are sure about the DOM position of the elements, you can change the .find() to .children()