How to replace all id from href?

- 1 answer

Ad

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?

Ad

Answer

Ad

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()

Ad
source: stackoverflow.com
Ad