-4

I have different pages which populate a div tag with a specific id based on the id inner text: here are some different example of pages with this div:

<div id="id_name">text page1</div>
<div id="id_name">text page2</div>
<div id="id_name">text page3</div>

I want to take only the inner text of second and fill a variable.

I try to use something like this:

if($("#id_name").length > 0 && $("#id_name").text() === "text page2") {
    site.text = $("#id_name").text();
} 
Teras
  • 1
  • 4
  • 1
    You HTML is invalid as you can't have duplicate IDs! – lshettyl Jul 23 '15 at 10:34
  • Do you really have multiple elements with the same id attribute on your page? Is site.text a variable name or is it an HTML element on your page? – t.h3ads Jul 23 '15 at 10:34
  • @Teras first of all you are supposed to have unique ID values for your html tags, you can't have id_name for all the three divs they need to be different. – Sumit Surana Jul 23 '15 at 10:35

3 Answers3

0

Try this:

if($("#id_name:eq(1)").length > 0 && $("#id_name:eq(1)").text() === "text page2") {
    site.text = $("#id_name:eq(1)").text();
} 

Hint use class instead of ID.

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Muhammad Atif
  • 1,050
  • 1
  • 9
  • 21
0
  1. Do not use the same id for multiple elements. See Why is it a bad thing to have multiple HTML elements with the same id attribute?
  2. Use classes instead
  3. You can use :contains()

if ($(".class_name:contains(text page2)").length > 0) {
  $('body').text("text page2");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="class_name">text page1</div>
<div class="class_name">text page2</div>
<div class="class_name">text page3</div>
Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • @Teras, ok, even if they are different pages, the code should still working. Maybe I am misunderstanding something? – AmmarCSE Jul 23 '15 at 10:42
  • I can't change the html code. It is id. I want to use it in somewhere else and as default I have this information. So I though to check if this id exists and if its' innerText is equal to what I want. If both conditions true than I want to assign to the specific variable the inner text of id – Teras Jul 23 '15 at 10:46
  • Please is it possible to provide me a workaround like this one? – Teras Jul 23 '15 at 10:48
  • @Teras, if you must use the ids then change the code in my answer to use `if ($("[id="id_name"]:contains(text page2)")` instead – AmmarCSE Jul 23 '15 at 10:58
  • Why you use body instead of #id_name? – Teras Jul 23 '15 at 11:03
  • Why you don't assign the text to the variable I have like this ` site.text = $("#id_name").text();`? – Teras Jul 23 '15 at 11:09
0

Try this:

$("[id*='id_name']").each(function(){
    if ($(this).html() == "text page2"){
    site.text($(this).html());  
}
});
Rajan Goswami
  • 769
  • 1
  • 5
  • 17