-3

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?

shishir
  • 851
  • 3
  • 11
  • 27
  • 2
    Read [how to ask questions](http://stackoverflow.com/help/how-to-ask), have you actually did any research? googling "jquery accessing child elements" and "jquery edit attribute" gives you the answer quite fast. – saljuama Dec 23 '15 at 02:20
  • @AlexanderKolovsky Did my answer help? If so, please accept. If not, please give feedback? – Jonathan Lam Dec 23 '15 at 20:17

2 Answers2

2

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.generals, 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.

Community
  • 1
  • 1
Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
1

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