How to get text around an element? - javascript

If I have
<div id='wrapper'>
<fieldset id='fldset'>
<legend>Title</legend>
Body text.
</fieldset>
</div>
How could I retrieve the "Body text" without retrieving the text inside of legend tag?
For instance, if I wanted to see if the text inside the fieldset contains the word "body" and change that word, while ignoring whatever might be in the legend? innerHTML retrieves all text from all children nodes.
Use of jQuery wouldn't be a problem.

$("#fldset").contents().eq(2).text();

Without a library --
var fldset = document.getElementById("fldset"),
txt = fldset.lastChild.textContent || fldset.lastChild.innerText;
alert(txt);

This will get all the text nodes of fldset leaving out any other element and it's content:
var fldsetContent = $('#fldset').contents();
var text = '';
$(fldsetContent).each( function(index, item) {
if( item.nodeType == 3 ) text += $.trim($(item).text());
});
alert( text );
Live example

$('#fldset').clone().find('legend').remove().end().text()
But you should also search around the SO
Using .text() to retrieve only text not nested in child tags
Clip content with jQuery

I can't think of a way other than
$("#result").html($("#wrapper").text().replace($("legend").text(),""));
but there should be a more elegant way. You can also create a new element as a copy of this one, remove all the children and get text. Hmm... That would be:
var newElement = $("#fldset").clone();
newElement.children().remove();
$("#result").html(newElement.text());
So doesn't matter how many and which type of children node has, this would work. Here: http://www.jsfiddle.net/wFV4c/

To turn all plain text nodes inside the field set red:
jQuery.each($('#fldset').contents(),function(index,value){
if(value.textContent == value.nodeValue){
$(this).wrap('<span style="color:red;" />')
}
});

Related

Change text id span via JavaScript [duplicate]

This question already has answers here:
How can I change an element's text without changing its child elements?
(16 answers)
Closed 1 year ago.
I have next html:
<label for="user_name">
<abbr title="required">*</abbr>
Name
</label>
And I want to change label caption to Title with jquery. So I do
$('label[for=user_name]').html('Title')
And it replaces all inner html (including abbr tag)
So, what's the easiest way to replace only Name?
If you use contents() method it will also return text nodes. Since jQuery doesn't have text node methods, convert last node to a DOM node
$('label[for="user_name"]').contents().last()[0].textContent='Title';
Demo: http://jsfiddle.net/yPAST/1/
Sorry for the late reply... But here is a way to do so using only jQuery:
$('label').contents().last().replaceWith('Title');
It may not be the prettiest way, but this works:
var $label = $('label[for=user_name]');
$label.html($label.html().replace("Name", "Title"));
You can select only the abbr element, store it, and then replace the whole content with the stored element plus the changed caption:
​$('label[for="user_name"]').each(function(){
var a = $(this).children('abbr');
$(this).html(a).append('Title');
});
See this fiddle​
you can use replace accomplish this
var html = $('label[for=user_name]').html().replace('Name','Testing');
$('label[for=user_name]').html(html);
check it : http://jsfiddle.net/DyzMJ/
Evans solution added to jquery fn to make it's use comfortable:
// get/change node content not children
jQuery.fn.content = function( n ){
var o = $(this).clone();
var c = o.children().remove();
if (typeof n === "string" ){
o.html(n);
$(this).html(c).append(n);
}
return o.html();
}
Usage :$('myselector').content('NewContentString');
This is the solution that worked for the most browsers
$('label[for="user_name"]').contents().last()[0].nodeValue = 'Title';
This one came close but gave issues in ie8 since textContent is not supported
$('label[for="user_name"]').contents().last()[0].textContent='Title';
if you are manipulating more than 1 label you can select each label and replace text with jquery:
$('label[for="user_name"]').contents().last().replaceWith("Title");
and for the second label :
$('label[for="user_lastname"]').contents().last().replaceWith("Title2");
and so on ...

Using jQuery to find matching text in any child text node?

I'm a bit rusty on my jQuery (been a few years!) I have to assume this has been asked 100 times but I'm not searching for the right terms it seems.
I'm trying to grab all of the descendant text nodes of an object, and then, if there's a match to a text string, do something with that object. Here's why I have now:
$(".my-item").each(function(){
var content = $(this).find('*').text();
if (content.indexOf('mySearchString'>0)){
//do something
}
})
I can't seem to get this to find all text, however. Just the direct descendents. Sample HTML:
<div class="my-item">
this text is part of the var 'content'
<div>
this text is not
</div>
</div>
You have to access the textContent of each node, and you could do directly in the filter, and return the matches, or use a regular each loop if you want to work with them directly
$(".my-item").each(function(){
var $children = $(this).children();
$children.contents().each(function(i,node){
if (node.nodeType === 3 && node.textContent.indexOf('mySearchString') !== -1) {
//do something
}
});
});
FIDDLE

Use javascript to change text only in an element [duplicate]

This question already has answers here:
How can I change an element's text without changing its child elements?
(16 answers)
Closed 1 year ago.
Is there a simple way to change the text of an element only using vanilla javascript? In the code below, I thought that using .textContent, rather than .innerHTML would change the text and leave the image behind.
<head>
<script>
function change_stuff() {
var div = document.getElementById('to_change');
div.textContent = "OMG...it's an image!";
}
</script>
</head>
<body>
<div id="to_change">
This is a huge block of text that I want to replace while leaving the image in place
<img src="./the_image.jpg">
</div>
<button onclick="change_stuff();">
ThE dOER!!
</button>
</body>
I've also tried but had little to no success with many variations of this:
function change_stuff() {
var div = document.getElementById('to_change');
var text = div.textContent;
div.textContent = text.replace(text, "");
}
Any help would be appreciated
Get the first textNode by firstChild property and update the content.
function change_stuff() {
// get the first child node, in your code which is the text node
var t = document.getElementById('to_change').firstChild;
// update the text contents in the node
t.nodeValue = "";
// or t.textContent = "";
// or remove the node itself
// t.parentNode.removeChild(t)
}
<div id="to_change">
This is a huge block of text that I want to replace while leaving the image in place
<img src="./the_image.jpg">
</div>
<button onclick="change_stuff();">
ThE dOER!!
</button>
In the W3C DOM (Document Object Model), everything is a "node". Nodes come in different types (comment nodes, element nodes, attribute nodes and even text nodes). It may seem counter-intuitive that an element like div that doesn't have any nested elements that can contain text inside it actually does implicitly have a child element within it that contains the raw text and that element is a text node.
In order to access that (which will be separate from other elements within the div, you can navigate to the div and look for (in this case, it's firstChild because the text comes first and the image is second.
Also, when it comes to replacing the original text with something else...You were trying to call the .replace() string function on the div and not the text within the div. You can isolate just the text of the div by navigating to the text node within it and working just on that.
function change_stuff() {
// Get a reference to the div element's text node which is a child node
// of the div.
var divText = document.getElementById('to_change').firstChild;
// Get the current text within the element:
var text = divText.textContent;
// You can do whatever you want with the text (in this case replace)
// but you must assign the result back to the element
divText.textContent = text.replace(text, "");
}
<div id="to_change">
This is a huge block of text that I want to replace while leaving the image in place
<img src="./the_image.jpg">
</div>
<button onclick="change_stuff();">
ThE dOER!!
</button>
Or the pragmatic:
function change_stuff() {
var div = document.getElementById('to_change'),
img = div.getElementsByTagName('img')[0];
div.innerHTML = "OMG...it's an image!";
div.appendChild(img);
}
<div id="to_change">
This is a huge block of text that I want to replace while leaving the image in place
<img src="./the_image.jpg">
</div>
<button type="button" onclick="change_stuff();">
ThE dOER!!
</button>
You need to use innerText to set the text within the div (i.e.: div.innerText = replacement).
See Node.textContent - Differences from innerText.

Javascript : Replace Detect a string and replace html in a div after changing color

I am trying to change color of a part of strings. I have a list of DOM elements, and for each of them, the text can contain some hashtags. I would like to put in color all hashtags words which could be found in the text.
Here is the begin of the code :
var listOfText = document.getElementsByClassName("titleTweet");
for (var nodetext in listOfText) {
var divContent = listOfText[nodetext].innerHTML;
if (divContent.indexOf("#") !== -1) {
// Do job here
}
}
For example, divContent can be equals to "Hello my #friends ! How are you ?"
I would like to update the dom elements to put in red color the word "#friends".
I don't know how to do that using javascript or jQuery.
You can use a regexp to find the hastags and wrap them with html. Then use the .html() method to replace the original element's html with the new string.
Example snippet
$('#myDiv').replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
Working example - http://jsfiddle.net/4p4mA/1/
Edited the example to work on all divs on the page.
Note: This will only work so long as your element only contains text, because it is replacing all the child nodes with its text value.
use regex for this, find text having hashtag and replave that in span tag for each element.
$('.titleTweet').each(function(){
var $this=$(this);
$this.html($this.text()
.replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
});
See demo here
.innerHTML is a poor basis to starting replacing text. You'll want to navigate down to the text nodes and use .nodeValue to get the text. Then you can start splitting up the text nodes.

jQuery - setting an element's text only without removing other element (anchor)

I have an element like this:
<td>
<a>anchor</a>
[ some text ]
</td>
And i need to set it's text in jQuery, without removing the anchor.
The element's contents could vary in order (text before or after), and the actual text is unknown.
Thanks
New Update
This is what i came up using, assumes only a single text node:
function setTextContents($elem, text) {
$elem.contents().filter(function() {
if (this.nodeType == Node.TEXT_NODE) {
this.nodeValue = text;
}
});
}
setTextContents( $('td'), "new text");
Neal's answer is my suggestion. jQuery doesn't have a way to select text nodes How do I select text nodes with jQuery?.
Changing your HTML structure will make for the simplest code. If you can't do it, you can just use the childNodes property looking for nodes of type 3 (TEXT_NODE)
Here's some sample code that assumes the last node is the node you want to edit. This is a better approach than replacing the entire contents of the td because you could lose event handlers when you recreate the HTML
$('a').click(() => console.log('<a> was clicked'))
$('#btn').click(() =>
$('.someClass').get(0).lastChild.nodeValue = " New Value");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='someClass'>
anchor [ some text ]
</div>
<button id='btn'> Change text without losing a tag's handler</button>
If it is possible to put the text in a span:
<td id='someID'>
<a>anchor</a>
<span>[ some text ]</span>
</td>
You can do:
$('td#someID span').text('new text')
Without changing markup:
Live Demo
var anchor = $('td').find('a').clone();
$('td').text('{ some other text }').prepend(anchor);

Categories

Resources