This question already has answers here:
How do I select text nodes with jQuery?
(12 answers)
Closed 8 years ago.
Is it possible to use JQuery to hide the input elements plus the text after the input? The code is generated, so I cannot change the text, wrap it in a span or alter it in any way.
<label>Event Location <span class="req">*</span></label><br>
<input type="radio" name="a22" id="a22_0" value="Lafayette LA">Lafayette LA<br>
<input type="radio" name="a22" id="a22_1" value="Houston TX">Houston TX<br>
<input type="radio" name="a22" id="a22_3" value="San Antonio TX">San Antonio TX
You need to iterate the parent elements (TDs in your example added as an answer), find all the text elements that follow a radio button, then wrap them in hidden spans:
e.g.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/6gzfLorp/3/
$('td').contents().each(function (e) {
if (this.nodeType == 3 && $(this).prevAll(':radio').length) {
$(this).wrap($('<span>').hide());
}
});
Note: Your question is a little ambiguous, but it would appear from your answer you have TDs which you could just hide all contents of the TD using:
http://jsfiddle.net/TrueBlueAussie/6gzfLorp/7/
$('.set-cities td').each(function (e) {
$(this).contents().wrapAll($('<span>').hide());
});
It is wrapped in a td tag. Here's what I have for now:
$("label:contains('Event Location')").parent("td").wrap("<span class='set-cities'></span>");
$('.set-cities').empty();
$('.set-cities').append("<td><label>Event Location <span class='req'>*</span></label><br><input type='radio' name='aa2' id='aa2_1' value='Houston TX' checked='checked'>Houston TX<br></td>");
I just going to change the whole block of text rather than just the city name.
In case you wanted to replace the text node directly, here's a way to do it. I borrowed from https://stackoverflow.com/a/298758/728393 and tailored it to your situation
function replaceTextAfter(selector,newtext){
var textnode = $(selector).parent().contents() // we need to contents as a collection
.filter(function(){
return this.nodeType == 3 && $(this).prev().is($(selector)); //return true if node is text and the previous node is our selector
});
textnode[0].data = newtext; //change the text
}
replaceTextAfter('#a22_0','abc');
http://jsfiddle.net/z606no23/
Thi delete all text after an element done, until a new tag
http://jsfiddle.net/alemarch/hm7ey6t5/
function deleteElemPlusText( elem ) {
var contestoHtml = $(elem).parent().html()
var thisHtml = $(elem).get(0).outerHTML // $(elem).outerHTML()
var re = new RegExp(thisHtml + "([^<])*")
var newContesto = contestoHtml.replace(re, "")
$(elem).parent().html(newContesto)
}
function deleteAllElemsPlusText( toDelete ) {
var x = $(toDelete).length;
for (var i = 0; i < x; i++) {
deleteElemPlusText($(toDelete).eq(0))
}
}
deleteAllElemsPlusText( "input[type=radio]" )
note: not all browser have outerHTML properties access, but you can use this jquery plugin http://www.darlesson.com/jquery/outerhtml/
Related
This question already has answers here:
How to get the text node of an element?
(11 answers)
Closed 6 months ago.
I am trying to learn DOM scrapping using jquery. I have a structure like this
<p>
A. liver.
<br> B. diaphragm.
<br> C. esophagus.
<br> D. pancreas.
</p>
How can I iterate in this P tag and get TEXT NODES in an array,, e.g [A-Text,BText,CText,DText], I do not want <br> tag.
Please help I could not figure it out, how to loop in P tag childs and segregate text nodes.
Thanks
To do this using jQuery you can use a combination of contents() to get all the nodes within the parent, then filter() to get the textNodes only. Try this:
var textNodeArray = $('p').contents().filter(function() {
return this.nodeType == Node.TEXT_NODE && this.textContent.trim();
}).get();
/* for demo purposes */
textNodeArray.forEach(function(node) {
console.log(node.textContent.trim());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
A. liver.
<br>B. diaphragm.
<br>C. esophagus.
<br>D. pancreas.
</p>
The solution using .contents(), .filter() and .map() functions:
var textNodes = $('p').contents().filter(function(){
return this.nodeType === 3;
}).map(function(i, n){
return n.nodeValue.trim();
}).get();
console.log(textNodes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
A. liver.
<br> B. diaphragm.
<br> C. esophagus.
<br> D. pancreas.
</p>
You can use contents function to get the children of the p element (including text and comment nodes) and then use filter to reduce collection to only nodes of text type.
var arr = [];
var getTextNodesContent = function(el) {
return $(el).children().addBack().contents().filter(function() {
var isTextNode = this.nodeType == 3;
if (isTextNode) {
arr.push($(this).text().trim())
}
return this.nodeType == 3;
});
};
getTextNodesContent($('p'))
console.log(arr);
I have input tags on the page that are generated dynamically using JS.
They are initialized using $("#input1").val(value). How can I find specific input elements base on text?
The values are initialized as follows:
$("input[name='DeviceIP']").each(function(index,elem){$(elem).val(value)});
The solution I am using now is to select all the inputs I want to inspect and then using find.
$("[name='DeviceIP']").filter(function(index, elem) {
var res = false;
var _this = this;
$("[name='DeviceIP']").each(function(index2, elem2) {
if(elem2 !== _this) {
if(_this.value === elem2.value) {
errMessage = "error text";
res = true;
}
}
});
return res;
}
I looked at the question here but the ":contains" didn't find them for some reason(maybe because there is no value attribute?)
"$("input[name='DeviceIP'][value='your_value_here']")
element.value is also an attribute, so You can define it in Your query ;)
Still, you shouldn't perform such query very often if You have a lot of elements.
I would also suggest You to create map, with values as keys, and nodes as values.
Suppose you have an input field like
<input type="text" value="5" name="DeviceIP">
<input type="text" value="8" name="DeviceIP">
you want the element with specific value. so you can do this,
alert($("input[name='DeviceIP'][value='5']").val());
Here is the fiddle.
If your value is dynamic, say for example your searching value is 8.so you can do this in a way,
var val = 8;
alert($("input[name='DeviceIP'][value='"+val+"']").val());
This question already has answers here:
jQuery - rule for "does not contain element"
(2 answers)
Closed 8 years ago.
<div id="I">
<h3></h3>
<div class="C">
<ul>...</ul>
</div>
</div>
Using JQuery or JavaScript, how can I hide the whole id="I" element if the element <ul> does not exist?
You can use the following Jquery to determine if a ul element exists inside of the div with id="I"
$(document).ready(function(){
var size = $("#I ul").length;
if (size === 0)
$("#I").hide();
});
JsFiddle
EDIT:
I've updated my script since it wouldn't work if you have multiple div tags with an id of "I". Based on your description, you would like to remove all div tags with id of "I" that do not contain a ul element. Here is the updated JsFiddle that meets your question's requirement: enter link description here
Here is the code to do just that:
$(document).ready(function(){
$("div").each(function(index, element){
var id = $(this).attr("id");
var numOfUl = $(this).find("ul").length;
if (id == "I" && numOfUl === 0){
$(this).hide();
}
});
});
Try this:
$("#I:not(:has(>ul))").hide();
DEMO
$.fn.isNot = function(trueFalse) {
var elem = $(this);
var _isNot = elem.is("*");
var _parent = $(elem.selector.split(" ").slice(0, 1)[0]);
return _isNot
? trueFalse(_isNot, elem, _parent)
: trueFalse(_isNot, _parent)
};
$("#I ul").isNot(function(trueFalse, parent) {
console.log(trueFalse, parent);
if (!trueFalse) {
parent.hide()
};
});
http://jsfiddle.net/guest271314/ns09astu/
This question already has answers here:
javascript variable corresponds to DOM element with the same ID [duplicate]
(3 answers)
Closed 9 years ago.
I have multiple spans
<span id ="myId">data1</span>
<span id ="myId">data2</span>
<span id ="myId">data3</span>
<span id ="myId">data4</span>
<span id ="myId">data5</span>
I want to delete text inside all span on single button click.
I tried this on button click in javascript
document.getElementById("myId").innerHTML = "";
but it is removing text from only 1st span
IDs are unique, Classes are repeatable
The purpose of an id in HTML is to identify a unique element on the page. If you want to apply similar styles or use similar scripts on multiple elements, use a class instead:
<span class="myClass">data1</span>
<span class="myClass">data2</span>
<span class="myClass">data3</span>
<span class="myClass">data4</span>
<span class="myClass">data5</span>
<input type="button" id="clearbutton" value="Clear Data">
Now let's remove the text
Now, you can select all of these elements and set their text to anything you want. This example uses jQuery, which I recommend because older versions of IE don't support getElementsByClassName:
$('#clearbutton').click(function() {
$('.myClass').text('');
});
Link to Working Demo | Link to jQuery
Or in Vanilla JS
If you're not worried about supporting IE, you can do this with vanilla JavaScript:
function clearSpans() {
var spans = document.getElementsByClassName("myClass");
for(var i=0; i < spans.length; i++) ele[i].innerHTML='';
}
Link to Working Demo
Note: You can add getElementsByClassName to IE
I wouldn't recommend doing this because it's simpler and more widely accepted to just use jQuery, but there have been attempts to support older IEs for this function:
onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
Link to source
Dont give same ID to more than one one tag, use class instead
<span class ="myId">data1</span>
<span class ="myId">data2</span>
<span class ="myId">data3</span>
<span class ="myId">data4</span>
<span class ="myId">data5</span>
call this function to clear
function clearAll()
{
var ele= document.getElementsByClassName("myId");
for(var i=0;i<ele.length;i++)
{
ele[i].innerHTML='';
}
}
You are using a DOM method that relies to the DOM of ID, that is, per DOM, there can only be one element with the same ID.
However, you do not use the id attribute that way in your HTML, so instead you are looking for the selector to query all elements with the id myId, you perhaps know it from CSS:
document.querySelectorAll("#myId").innerHTML = '';
This does not work out of the box, you also need to add the innerHTML setter to the NodeList prototype, but that is easy:
Object.defineProperty(NodeList.prototype, "innerHTML", {
set: function (html) {
for (var i = 0; i < this.length; ++i) {
this[i].innerHTML = html;
}
}
});
You find the online demo here: http://jsfiddle.net/Pj4HD/
var spans=document.getElementsByTagName("span");
for(var i=0;i<spans.length;i++){
if(spans[i].id=="myId"){
spans[i].innerHTML="";
}
}
Although I suggest you don't keep same IDs
http://jsfiddle.net/YysRp/
This question already has answers here:
How can I change an element's text without changing its child elements?
(16 answers)
Closed 9 years ago.
Inside the "td" tag, how do I replace the "BMW" word after the "span" tag without removing the whole "span" tag script? (In JQuery).
The word "BMW" is wildcard wording. It can be "Ford", "Volvo", etc.
I'm using JQuery version 2.0
$('#'....).???
<td>
<span column="17" style="cursor:pointer"></span> BMW
</td>
Just use nextSibling if the text node is the next sibling like in the question:
$('span[column="17"]').get(0).nextSibling.nodeValue = 'Volvo';
FIDDLE
Try this out... Note that I'm omitting any text nodes that are whitespace:
$("YOUR TD SELECTOR HERE")
.contents()
.filter(
function() {
return this.nodeType == 3 && $(this).text().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
)
.text('text to replace here');
You can use .contents(), .filter(), and .replaceWith():
EXAMPLE:
$('table').find('td')
.contents()
.filter(function() {
return this.nodeType === 3;
})
.replaceWith("hello world");
});
http://jsfiddle.net/V4wF5/1/
Edit: I forgot the closing end parenthesis for the first call.
Not sure how you are identifying the column so you may need to change the selector. This is a straight search and replace. You did want to only replace the word BMW, correct?
// Example: $(table.cars td)
$('td').each(function()
{
var repl = $(this).html().replace('BMW', 'Ford');
$(this).html(repl);
});
I do not know any nice jQuery solution, so I provide low level javaScript way. Sorry for that, but believe it helps.
$("td").each(function(i,v){
for (var i = 0;i < v.childNodes.length;i++){
if (v.childNodes[i].constructor.name=="Text"){
v.childNodes[i].nodeValue=v.childNodes[i].nodeValue.replace(/BMW/,"Volvo");
}
}
});
Edit:
It's little bin incompatible so it's better version:
$("td").each(function(i,v){
for (var i = 0;i < v.childNodes.length;i++){
if (v.childNodes[i] instanceof Text){
v.childNodes[i].nodeValue=v.childNodes[i].nodeValue.replace(/BMW/,"Volvo");
}
}
});
Here I bring it to life: http://jsbin.com/ItotOPo/1/edit?html,js,output