Get the value of an element child in javascript - javascript

I'm trying to get the value of an element child. Here is the element :
<li id="1" style="display:normal">
<h2 id="label_lg">Temp Set (º<span class="degsign">C</span>)</h2>
<p id="ihi" style="color:teal;font-size:3vw;">--</p>
</li>
I would like to get the value of <p></p>, if possible in javascript. I've tried to use
document.getElementById(1).childNodes[1].nodeValue;
and
var o = document.getElementById(i).children
o[1].nodeValue
Nothing worked, the alert always returns null.

Since you've specified jQuery:
$('#1 p').text();
As simple as that.

You can use following:
innerText || textContent
These will give you text of element. If you have nested elements like a small tag inside p, you will get text of all.
innerHTML
This will return HTML of the element. If you have nested elements, it will not return text, but a raw html of that element. But if element does not have a child, then output will be same.
(function() {
var parent = document.getElementById('1');
var _innerText = parent.innerText;
var _innerHTML = parent.innerHTML;
var _textContent = parent.textContent;
console.log(_innerText, _innerHTML, _textContent)
})()
<li id="1" style="display:normal">
<h2 id="label_lg">Temp Set (º<span class="degsign">C</span>)</h2>
<p id="ihi" style="color:teal;font-size:3vw;">--</p>
</li>

Try:
var pString = document.getElementById("ihi").value;
and to change the value:
pString.innerHTML = "Your string"

with JS
alert(document.getElementById('ihi').innerHTML)
<li id="1" style="display:normal">
<h2 id="label_lg">Temp Set (º<span class="degsign">C</span>)</h2>
<p id="ihi" style="color:teal;font-size:3vw;">--</p>
</li>
with JQUERY:
alert($('#ihi').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="1" style="display:normal">
<h2 id="label_lg">Temp Set (º<span class="degsign">C</span>)</h2>
<p id="ihi" style="color:teal;font-size:3vw;">--</p>
</li>

You can use the innerText property:
alert(document.getElementById(1).childNodes[1].innerText);
// Alerts "--"
In case you want to use jQuery:
alert($("1").child("#ihi").html())

Related

Catch a html tag value with javascript

I have a div tag like
<div id="123" reference="r045">
Now I wanna save the value of the reference. I tried it with
var reference = document.getElementbyName("reference");
Didnt work. Any ideas?
Thanks :)
getElementbyName gets an element by its name.
The reference attribute:
Is not a name attribute
Is not valid HTML at all
So start by writing valid HTML:
<div id="123" data-reference="r045">
Then get a reference to that element:
const div = document.getElementById('123');
Then get the data from it using the dataset API:
console.log(div.dataset.reference);
Live demo
const div = document.getElementById('123');
console.log(div.dataset.reference);
<div id="123" data-reference="r045"></div>
You can use document.querySelectorAll('[reference]') if you have multiple div with same attribute.
var reference = document.querySelectorAll('[reference]');
console.log(reference);
<div id="123" reference="r045"></div>
But if you have only one div with reference attribute then use querySelector:
var reference = document.querySelector('[reference]');
console.log(reference);
<div id="123" reference="r045"></div>
var reference = document.getElementById("123").getAttribute("reference");
var x = document.getElementById("123").getAttribute("reference");
console.log(x);
<div id="123" reference="r045"></div>

get the inner value of list item when clicked through javascript

I have a users list, I am retrieving all users from database and listing them as below
<div class="online-users">
<ul id="outer-list">
#foreach($users->getUsers() as $user)
{{--remove white spaces from name--}}
<?php $name = str_replace(' ','-',$user->name);?>
<li onclick="openMessageBox()" id="user" class="inner-list-item">{{$user->name}}</li><br>
#endforeach
</ul>
</div>
This is what I want to achieve when we click on any list item, I want to grab that user's name. But what I have tried so far is
<script>
function openMessageBox(){
var user_id = document.getElementById('outer-list');
user_id=user_id.getElementsByClassName('inner-list-item').innerHTML;
window.alert(user_id);
document.getElementById('message-box').style.display="block";
}
</script>
it only gives me access to the user's name if I use [index] with
user_id=user_id.getElementsByClassName('inner-list-item')[5].innerHTML;
I do not want to explicitly tell the index every time. Is there any way to achieve this?
You need to pass current ref as a parameter.
<input id="theId" value="test" onclick="doSomething(this)" />
// Javascript
function(elem){
var value = elem.value;
var id = elem.id;
...
}
You can pass in the element reference to the function:
<li onclick="openMessageBox(this)" id="user" class="inner-list-item">{{$user->name}}</li><br>
and then get the username by simply reading the element's textContent (this will work for attributes as well, as #rybo111 suggested in the comments):
function openMessageBox(el){
var name = el.textContent;
}
Simple live example:
function openMessageBox(el){
var name = el.textContent;
alert(name);
}
<ul>
<li onclick="openMessageBox(this)">Alice</li>
<li onclick="openMessageBox(this)">Bob</li>
</ul>
And btw. you'll end up having duplicate user IDs on those li elements.

Class name to find nested tagname and assign value in Javascript

I have the following markup which I can't modify:
<li class="campID">
<label for="input_2_14">Name</label>
<div>
<input name="input_14" id="input_2_14" type="text" value="" class="medium" tabindex="11">
</div>
</li>
I want to select the input and change its value using vanilla JS (assume jQuery is not available).
I can't use the input name or ID as these are dynamic and will change.
I have tried the following but it doesn't seem to work:
(function(){
var listElement = document.getElementsByClassName('campID');
var myInput = listElement.getElementsByTagName('input');
myInput[0].value = 'John';
})();
If you are targeting IE8 and above then:
document.querySelector("li.campID input").value="John";
else:
Assuming for the first LI and Input alone:
var liListItem = document.getElementsByClassName("campID")[0],
inputElement = liListItem.getElementsByTagName("input")[0];
inputElement.value = "John";
document.getElementsByClassName("campID") returns you NodeList. So you need to probably loop over and do.
querySelector() and querySelectorAll() complete CSS selector.
querySelector() returns only first matching Element node within Nodes.
Whereas
querySelectorAll() returns a list of Node containing all matching Element nodes within the Nodes.
You have to use querySelectorAll() selector for select multiple purpose,
var in = document.querySelectorAll(".campID input");
in.value = 'John';
console.log(in);
Console return:
[input#input_2_14.medium, value: "John", item: function]
I know it's been long time. Just thought of posting the solution that worked for me. For the below HTML
`
<li class="list-summary-item">
<span>Registration number</span>
<span class="reg-mark">LT08 YJA</span>
</li>
<li class="list-summary-item">
<span>Colour</span>
<span><strong>BLACK</strong></span>
</li>
<li class="list-summary-item">
<span>Make</span>
<span><strong>VAUXHALL</strong></span>
</li>
`
<br>
document.getElementsByClassName('list-summary-item')[2].getElementsByTagName('span')[1].getElementsByTagName('strong')[0].innerHTML <br>
gives VAUXHALL.

getting text content of specific element

I'm trying to get element text content only ignoring element's descendants, for instance if you look at this HTML:
<p>hello <h1> World </H1> </p>
for element "P" the right output should be ONLY "hello ".
I have checked the function: "element.textContent" but this returns the textual content of a node and its descendants (in my example it will return "hello world").
Thanks,
Considering this HTML:
<div id="gettext">hello <p> not this </p> world?</div>
do you want to extract "hello" AND "world"? if yes, then:
var div = document.getElementById('gettext'), // get a reference to the element
children = [].slice.call(div.childNodes), // get all the child nodes
// and convert them to a real array
text = children.filter(function(node){
return node.nodeType === 3; // filter-out non-text nodes
})
.map(function( t ){
return t.nodeValue; // convert nodes to strings
});
console.log( text.join('') ); // text is an array of strings.
http://jsfiddle.net/U7dcw/
well behind it is an explanation
$("p").clone() //clone element
.children() //get all child elements
.remove() //remove all child elements
.end() //get back to the parent
.text();
The answer i have is the same provided in couple of other answer. However let me try and offer an explanation.
<p >hello<h1>World</h1> </p>
This line will be rendered as
hello World
If you look at this code it will be as follow
<p>hello</p>
<h1>World</h1>
<p></p>
With the <p> tag you do not necessarily need the closing </p> tag if the paragraph is followed by a element.
Check this article
Now you can select the content of the first p tag simply by using the following code
var p = document.getElementsByTagName('p');
console.log(p[0].textContent);
JS FIDDLE
You can use the childNodes property, i.e.:
var p = document.querySelector('p');
p.childNodes[0]; // => hello
jsFiddle
Change your html to
<p id="id1">hello <h1> World </h1> </p>
Use this script,
alert(document.getElementById("id1").firstChild.nodeValue);
Try to provide id for the element which you want to do some operation with that.
Below is the working example, it show output as "hello" as you expected.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showParagraph()
{
alert(document.getElementById('test').innerHTML);
}
</script>
</head>
<body>
<p id="test">hello <h1> World </H1> </p>
<input type="button" onclick="showParagraph()" value="show paragraph" />
</body>
</html>
Plain texts are considered as nodes named #text. You can use childNodes property of element p and check the nodeName property of each item in it. You can iterate over them and select just #text nodes.
The function below loops over all element in document and prints just #text items
function myFunction()
{
var txt="";
var c=document.body.childNodes;
for (i=0; i<c.length; i++)
{
if(c[i].nodeName == "#text")
txt=txt + c[i].nodeName + "<br>";
};
return txt;
}
EDIT:
As #VisioN said in comments, using nodeType is much more safer (for browser compatibility) and recommended.

jQuery find and replace string

I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:
$(body).html($(body).html().replace('lollypops', 'marshmellows'));
This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:
search for the string
find the closest parent element
rewrite only the closest parent element
replace this even in attributes, but not all, for example replace it in class, but not in src
In example, I would have structure like this
<body>
<div>
<div>
<p>
<h1>
<a>lollypops</a>
</h1>
</p>
<span>lollypops</span>
</div>
</div>
<p>
<span class="lollypops">Hello, World!</span>
<img src="/lollypops.jpg" alt="Cool image" />
</p>
<body>
In this example, every occurrence of "lollypops" would be replaced, only <img src="... would remain the same and the only elements that would actually be manipulated would be <a> and both <span>s.
Does anybody know how to do this?
You could do something like this:
$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});
It will be better to mark all tags with text that needs to be examined with a suitable class name.
Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.
You could do something this way:
$(document.body).find('*').each(function() {
if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
$(this).removeClass('lollypops');
$(this).addClass('marshmellows');
}
var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
var text = $(this).text(); //getting just current node text
text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
$(this).text(text); //setting text
$(this).append(tmp); //re-append 'foundlings'
});
example: http://jsfiddle.net/steweb/MhQZD/
You could do something like this:
HTML
<div class="element">
<span>Hi, I am Murtaza</span>
</div>
jQuery
$(".element span").text(function(index, text) {
return text.replace('am', 'am not');
});
Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.
$('.hightlight').each(function(){
//highlight_words('going', this);
var high = 'going';
high = high.replace(/\W/g, '');
var str = high.split(" ");
var text = $(this).text();
text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
$(this).html(text);
});
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);
Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.
HTML:
<div>
<div>
<p>
<h1>
<a class="swapText">lollipops</a>
</h1>
</p>
<span class="swapText">lollipops</span>
</div>
</div>
<p>
<span class="lollipops">Hello, World!</span>
<img src="/lollipops.jpg" alt="Cool image" />
</p>
jQuery:
$(document).ready(function() {
$('.swapText').text("marshmallows");
});

Categories

Resources