How to change child text only with jQuery? - javascript

I got a piece html code like this:
<div><span>span_text</span>div_text</div>
I want to change 'div_text' with jQuery, tried with $.text('changed_div_text') but failed, result like this which is not what I want.
let tmpl = '<div><span>span_text</span>div_text</div>'
let $ = cheerio(tmpl)
console.log($.text()) // span_textdiv_text
$.text('changed_div_text')
console.log($.text()) // changed_div_text
As you can see, text() function will change inner text also, hope someone know a way to solve this problem, thanks!

jQuery doesn't offer a lot of methods that act directly on text nodes. You can use contents to find all child nodes (including text nodes), and you can use filter to find only text nodes, and then you can modify their nodeValue to change their text. Example:
// Get just the text nodes
var textNodes = $("#target").contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
});
// In this case, I just replace the text with "Index n" where n is the index
textNodes.each(function(index) {
this.nodeValue = "Index " + index;
});
<div id="target"><span>span_text</span>div_text</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

you have to know the text div_text is the childNode of div,and it is kind of textNode
var div=document.createElement('div');
div.innerHTML='<div><span>span_text</span>div_text</div>';
div.childNodes[0].childNodes[1].textContent='test';
console.log(div.innerHTML);//<div><span>span_text</span>test</div>
if you want to change the text,you can change the value of the textNode,for example,change the textContent ,innerText or innerHTML,,,

your html code is <div><span>span_text</span>div_text</div>
for your understanding I am assuming a button with id btn. clicking this button the text will be changed
button code <button id="btn">change</button>
now if you want to change all the child text of the div then the below code will work fine.
$(document).ready(function(){
$("#btn").click(function(){
$("div > span").text("changed_div_text");
});
});
now if you only want to change the last child of the div then the code is below
$(document).ready(function(){
$("#btn").click(function(){
$("div > span:last-child").text("changed_div_text");
});
});
hope it will solve your issue

Related

Get text inside an element using javascript

I am trying to get a text content inside a div using jquery. But it returns 'undefined'. Please someone tell me what i'm doing wrong here. this is my code.
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text',function(){
var text = $(this).textContent;
console.log(text);
});
textContent is a property on native elements, not on jQuery objects. $(this) wraps this (which is a native DOM element) in a jQuery object.
Either stick to the native DOM api (and go with textContent) - which is what I'd recommend:
document.addEventListener('click', (e) => {
if (e.target.classList.contains('exc_text') {
console.log(e.target.textContent);
}
})
Or stick with jQuery if you have to (and use .text()):
$(document).on('click', '.exc_text', function(){
var text = $(this).text();
console.log(text);
});
You're reselecting the element with jQuery which you don't need to do. Try this
$(document).on('click','.exc_text',function(){
var text = this.textContent;
console.log(text);
});
The easiest way to solve this is to look in dev tools. All i did was break on the second link, and hovered over this, which showed me that it was an element so no need to reselect it...
You should use .text() instead of .textContent
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text',function(){
var text = $(this).text();
console.log(text);
});
Just simply use .text()
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text', function(){
var text = $(this).text();
console.log(text);
});

change text of an element without changing child elements

$('button').click(function(){ $(this).prev('label').append('<b>ed</b>').text('Press');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Click<b>ed</b></label>
<button>Here</button>
I want to keep the element <b></b> or any element exisiting changing the .text()
The steps i'm trying to handle is the following
.append('<b>ed</b>') at first i appended the new element <b>;
Driectly after appending the new element i changed the text to Press .text('Press');
What i'm trying to do is copying the added <b>ed</b> element before changing the text .text('Press'); then add it again after changing the text()
So it would be like
var element = $(this).prev('label').clone('b');
$(this).prev('label').append('<b>ed</b>').text('Press'+element+'');
The problem i keep getting the element value = [Object object]
Just use .html() method in order to display the text desired as HTML.
$('button').click(function(){ $(this).prev('label').html('Press<b>ed</b>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Click<b>ed</b></label>
<button>Here</button>
Another solution:
$('button').click(function(){ $(this).prev('label').empty().append('<b>ed</b>').html('Press'+$(this).prev('label').html());
})
In order to access the text part, you need to use .contents()
See this answer and comments for more info.
$("#x").append("<b> pressed</b>")
.contents().filter(function(){return this.nodeType == 3;}).first()
.replaceWith("well done");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='x'>Press</div>
Here is an example using .text() and .append(). Keep in mind that .text() will replace the element's content in its entirety, so it's important to use .append() last.
$('button').on('click', function() {
var boldedElem = $(this).prev('label').find('b');
$(this).prev('label').text('Press').append(boldedElem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Click<b>ed</b></label>
<button>Here</button>
Look for all <b> in this label, take the last one and modify its content using html()
$('button').click(function(){
var label = $(this).prev('label');
label.find('b').last().html('Press');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Click<b>ed</b></label>
<button>Here</button>

How to get value from a dynamic element

I need to get the value from a "p" element, I draw this "p" with jQuery and it's ok, then I have a button and when I click on it I want to display the value from "p" element but I don't get any information, here is a simple code example:
$(document).ready(function() {
$('#c').click(function() {
var p = $('#p1').val();
alert(p);
});
draw();
});
function draw() {
var html = "";
html += '<p id="p1">Hi</p>';
$('#d').html(html);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="c">Click</button>
<hr />
<div id="d">
</div>
How can I solve this? I don't get any console error.
Change :
var p = $('#p1').val();
To :
var p = $('#p1').text();
.val() only returns the value from input, textarea and select elements. If you just want to read the content of an element, you should use .text() or .html(). The first returns just the text, and the second – HTML content of an element.
Here is the quote from jQuery
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. When called on an empty
collection, it returns undefined.
So as #ehsan suggested, use .text() method if you want to get content as text.
.val() is used to get the value of input, select and textarea elements.
If you want to get the text inside an element (e.g: div, p, etc), you need to use .text().
So, in your case, you need to change this:
var p = $('#p1').val();
for this:
var p = $('#p1').text();
Note: If you want the full html code inside an element, you need to use .html().
Sources:
http://api.jquery.com/val/
http://api.jquery.com/text/
http://api.jquery.com/html/
you can also use var p = $('#p1').html();

Jquery remove element

I am basically trying to print the value of a button in the div with list class if the button is selected. Also remove the same value wwhen it is deselected. I am able to print the value successfully but not able to remove it. Could somebody please help me out with it.
var buttonSelect = $(".btn").click(function() {
if ($(this).hasClass('active')){
$(".list").append(this.value + " ")
}
else {
$(".list").remove(this.value)
}
});
You should rather append the content along with html element like span:
$(".btn").click(function() {
if ($(this).hasClass('active')){
$(".list").append('<span class="newval_'+this.value+'">'+this.value + "</span>");
}else{
$(".list").find('.newval_'+this.value).remove();
}});
The parameters from .remove() is a selector, just having a value in there that contains the content of the element you want to remove will not work. For example if I had this:
<li class="list">test</li>
Doing $(".list").remove("test") will not remove it. You will probably want to use the :contains selector (since you may have the value with spaces at the end). So in the example above doing $(".list").remove(":contains('test')") will remove the element. You can do the same thing in your case:
$(".list").remove(":contains('"+this.value+"')");
If you want to remove the element itself along with everything in it, just use jQuery’s remove() method.
$(document).ready(function() {
$("button").click(function() {
$("div").remove(); //remove Div element
});
});
You can see an example here: How to Remove Elements from DOM in jQuery

Check if div has less than two children

I've just started using jQuery, and can't get my head around this.
I need to check if a div contains anything but a h3 header tag.
The structure of the html is as follows:
<div id="myContainer">
<h3>A header that is always present</h3>
any html, plain text or empty
</div>
Here's the jQuery:
if ( $("#myContainer h3:only-child") ) {
$("#myContainer").css("display", "none");
}
The above will simply hide the div if there is no other html elements present, which is not what I intend since it will also contain plain text. I have tried with other selectors and functions, but I just can't seem to get it right.
Thanks in advance :)
I think you want a function which will tell you if the div contains just H3 or also has other elements. I don't think there is a direct jQuery selector for that, so I wrote a simple function to checkForJustH3.
DEMO - That shows how to hide div that just has H3.
Check out the below demo by editing the div contents and Hit Run to see the result.
DEMO
function containsJustH3 (el) {
var result = true;
$(el).contents().each (function() {
if (this.nodeName != 'H3') {
//check for blank line or empty spaces
if (this.nodeType == 3 && $.trim(this.nodeValue) == '') {
return true;
}
result = false;
return false;
}
});
return result;
}
And using the above function you can do something like,
if ( containsJustH3("#myContainer") ) {
$("#myContainer").css("display", "none");
}
Try:
$("#myContainer").children('h3').hide();
jsfiddle
You can wrap the 'plain text' in a p element and use this selector:
fiddle
$("#myContainer").children().not('h3').hide();
//Select all children but not the h3
HTML:
<div id="myContainer">
<h3>A header that is always present</h3>
<p>any html, plain text or empty</p>
</div>
You can use the length property to see how many children the div has
$("#myContainer").children('h3').length
The fundamental problem here is that jQuery methods like children will not get text nodes. If you want to see how many children a div has, and include the text nodes, you'll want to grab the actual dom node, and check the length of its childNodes property. This will include text nodes.
if ($("#myContainer")[0].childNodes.length > 1) {
var $cont=$('#myContainer'), $children=$cont.contents().not('h3');
if( ! $children.length) {
$cont.hide();
}
Using contents() method will check if there are tags or text nodes in element, check if the children object has length, if not hide the container
You can use $("#myContainer").contents().length to get the number of nodes, including text nodes. However, this includes the newline before the <h3>, etc.

Categories

Resources