1

Hello guys :) I can make this with PHP, but iam trying to make with JS. I have some div like this:

<div class="content" id="2"> This is message </div>
<div class="content" id="43"> Hello </div>
<div class="content" id="21"> some content... </div>

I want to get all "id" attributes inside in "content" class. And the all of the ""text"" aswell...

Have to looks like : x = array(2, 43, 21) and y= array(this is message, Hello, some content) After this i want to fetch foreach ...

foreach () {
echo x;
echo y  }

Want to looks like this :

2 this is message 

43 Hello

21 some content
6
  • 1
    Have to looks like says who? What is this for? What have you tried? Is this homework? Commented Jun 25, 2017 at 23:58
  • You can probably find answer to this here and here Commented Jun 26, 2017 at 0:02
  • @junaid this is different question. Commented Jun 26, 2017 at 0:04
  • @halid96 is it? The point is, if you won't research about your issue then even try? You can simply hire a programmer to do it for you. Commented Jun 26, 2017 at 0:05
  • @halid96 is it? The point is, if you won't research about your issue then even try? You can simply hire a programmer to do it for you. Commented Jun 26, 2017 at 0:05

1 Answer 1

2

First, you want to assign each of the DOM elements to a list with document.getElementsByClassName, and then loop through each of these, outputting based on the index in the loop. You can grab the ID and content of each of the elements with .id and innerHTML respectively.

This could be done with something similar to the following:

var list = document.getElementsByClassName("content");
for (var i = 0; i < list.length; i++) {
  console.log(list[i].id, list[i].innerHTML);
}
<div class="content" id="2"> This is message </div>
<div class="content" id="43"> Hello </div>
<div class="content" id="21"> some content... </div>

If you want to actually replace the contents to the DOM itself, rather than simply log to the console, you can use document.innerHTML:

var list = document.getElementsByClassName("content");
for (var i = 0; i < list.length; i++) {
  list[i].innerHTML = list[i].id + list[i].innerHTML;
}
<div class="content" id="2"> This is message </div>
<div class="content" id="43"> Hello </div>
<div class="content" id="21"> some content... </div>

Hope this helps! :)

Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much dude :) wish you happy life, i will try it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.