I want to remove the ( from the HTML below
I have tried the following. I know I'm not using correct syntax
jQuery('div li').text().replace('/\(//', '');
jQuery('div li').text().replace('/(/', '');
jQuery('div li').text().replace('\(\', '');
jQuery('div li').text().replace('(', '');
HTML
<li>This text remains but i need to remove ( <a>from the sentence</a></li>
The .replace() method does not change the string object it is called on. It simply returns a new string.
So you can use the jQuery .html() method (assuming you want to keep the <a>) to get the string, pass the method a function to do the replacement, and return the modified HTML with:
jQuery('div li').html(function() {
return jQuery(this).html().replace('(', '');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<ul>
<li>This text remains but i need to remove ( <a>from the sentence</a></li>
</ul>
</div>
The problem is that to replace the text, you need to put the text inside the parenthesis: text({here})
jQuery('li').text(jQuery('li').text().replace("(", ""))
or
var str = jQuery('li').text().replace("(", "");
jQuery('li').text(str)
See here for more info: https://api.jquery.com/text/#text2
To really be safe about things, you should save your jQuery, and then use each to iterate over each element.
Example:
var elems = jQuery('div li');
elems.each(function() {
var $this = $(this);
$this.text($this.text().replace('/\(//', ''));
});
Assigning ID or class to element will be better but here is your answer.
$('div li').text($('div li').text().replace("(",""));
My recommendation:
<li id="change">This text remains but i need to remove ( <a>from the sentence</a></li>
$('#change').text($('#change').text().replace("(",""));
Hi I think this should solve your problem:
$(document).ready(function(){
$('#btn').click(function(){
var elt = $("li"),
result= elt.html().replace(/\(/g, "");
elt.html(result);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li>This text remains but i need to remove (
<a>from the sentence</a>
</li>
<button id="btn">Remove (</button>
You can try this:
var newContent = $('div li').text().replace('(', '');
$('div li').html(newContent);
Try this:
jQuery('div li').text().replace(/([,.(])+/g, '');
Related
I have the following HTML:
<div id="foo">
<span>
X
1
</span>
<span>
X
2
</span>
<span>
X
Hello
</span>
</div>
I want to use jQuery to get only the following 1, 2 and hello in JS (that means no <a> tags or ). Please note that I do not want to affect the DOM itself. I just want to retrieve the text in an object such as an array.
This is what I have so far:
$('#foo span');
However I can't seem to remove the "a" tag.
The following does not seem to work either:
$('#foo span').remove('a');
I'm also aware that .remove() affects the DOM it self, and does not just retrieve the text.
Solution creates array by looping over each child and cloning it to do manipulation so dom stays intact
var values = $('#foo').children().map(function () {
var $clone = $(this).clone();
$clone.children().remove();
return $.trim($clone.text());
}).get();
console.log(values) /// ["1","2","Hello"]
DEMO
This piece of code will get that value for you:
$('#foo span').each(function(){
console.log($.trim($(this).html().substring($(this).html().lastIndexOf(" ") + 6)));
});
Working jsFiddle:
http://jsfiddle.net/mrwqs2nb/1/
Open the console, you will see:
1
2
Hello
Since your problem is not detailed , on the basis of your requirements , this can be done as below
var res=[];
$('#foo span').map(function(i){
var htm=$(this).text();
var htm_d=$(this).find('a').html();
htm=$.trim(htm.split("").reverse().join(""));
htm_d=$.trim(htm_d.split("").reverse().join(""));
res[i] = htm.substring(0,htm_d.length);
} );
alert(res);
LIVE http://jsfiddle.net/mailmerohit5/5bvavx0p/
Not sure what the rules of this game are, but if it can be asumed that what you want is on the right of the then this should do it:
$('#foo span').map(function() {
//Split at the space.
var parts = $(this).html().split(' ');
//Remove the first element from the list.
parts.shift();
//Join and return.
return parts.join('');
}).get();
Use jquery's contents - the api page has an example on how to extra text nodes while ignoring other elements.
var result = $("#foo span")
.contents()
.filter(function() {
// #text nodes
return this.nodeType === 3;
}).map(function() {
// get the value and trim it (also removes  )
return $(this).text().trim();
}).filter(function() {
// remove blanks
return this != "";
}).toArray();
$("#result").text(result.join());
Working fiddle
Try using selector $("foo span") , $.map() , String.prototype.match() with RegExp [0-9]+|[a-z]+[^\s+|\n+|" + el.querySelector(".no-want").textContent + "]", "ig" to match digit or characters a-z case insensitive , negating space character , or newline character , or ".no-want" element .textContent at index of parent span element
var res = $.map($("#foo span"), function(el, index) {
return el.textContent.match(new RegExp("[0-9]+|[a-z]+[^\s+|\n+|"
+ el.querySelector(".no-want").textContent.trim() + "]", "ig"))
});
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">
<span>
X
1
</span>
<span>
X
2
</span>
<span>
X
Hello
</span>
</div>
Try using RegEx to match what you want
$('#foo span').each(function () {
alert($(this).html().match(/[0-9]/));
});
JSFIDDLE
Im using the below code to replace the text within the h1 tag, but its not getting effected. I want to replace "sample" to "new sample". I'm doing wrong?
<div class="content">
<h2>sample</h2>
</div>
var t = jQuery('.content');
t.children("h2").each(function() {
var contents = jQuery(this).contents();
jQuery(this).replaceWith(new sample);
});
use .html() to set html.try this:
$('.content h2').html('new sample');
Working Demo
If you want to replace some part of content then try this:
jQuery('.content h2').each(function(i, v) {
$v = $(v);
$v.html($v.html().replace('sample', 'new sample'));
});
jsFiddle
Use jQuery's .text()
$(".content h2").text("new sample");
FIDDLE
You can do that without jQuery:
var elem = document.getElementsByTagName('h2')[0];
elem.innerHTML = "New Value";
Set .text()
t.children("h2").text('new sample'));
If you want to set .html() content
t.children("h2").html('new sample'));
Child Selector (“parent > child”)
$('.content > h2').html('new sample');
How may I target certain links in list items using Javascript to remove certain characters?
For example I have the following code:
<dd class="xments">
<ul>
<li>"blah blah",</li>
<li>"lo lo",</li>
<li>"hhe he"</li>
</ul>
</dd>
I wish to remove the " and , for each list item. Please could some one help?
$("a").text(function(_, text) {
return text.replace('"', '');
return text.replace(',', '');
});
Doesn't seem to do it for me. How do I target only items in this list and not all a tags in the doc?
$('a').each(function (i, e) {
$(e).text($(e).text().replace(/[",]/g, ''))
});
yours with regexp (and additional conditions):
$("dd.xments ul li a").text(function(idx, text) {
return text.replace(/[",]/g, '');
});
$("a").text(function(_, text) {
var txt=text.replace('"', '');
txt=txt.replace(',', '');
this.innerText=txt;
});
To target only items in your list, add a class to each item. Change $("a") with $("classname")
$(document).ready(function(){
$('ul li').each(function(){
var that = $(this).children();
var txt = $(that).html();
txt = txt.replace(/["']/g, '');
$(that).html(txt.replace(',',''));
});
});
Fiddle
Check this Demo jsFiddle
jQuery
$("a").text(function(el, text){
return text.replace(/[",]/g, '');
});
Result
blah blah
lo lo
hhe he
Pattern
/[",]/g
Here I Check RegExr
I have simple list:
<ul id="tabs_nav">
<li id="t_00">data</li>
<li id="t_01">data</li>
<li id="t_02">data</li>
<li id="t_03">data</li>
</ul>
Now: How do I get the html of the first element, depending on what is ID. I would add that all of ID's change dynamically with the click of the button. This is my code:
btn.on('click',function(){
var ladder_nav_tabs = $('#tabs_nav'),
first_ladder_element_inset_id = ladder_nav_tabs.find('li').first().attr('id'),
first_ladder_element_inset_html = ladder_nav_tabs.find(first_ladder_element_inset_id).html();
console.log(first_ladder_element_inset_html);
});
Thx for help.
Seems you are missing the id selector #.
You are trying to get the html from the selector:
ladder_nav_tabs.find(first_ladder_element_inset_id).html();
This won't work as an id selector needs the #. Like this:
ladder_nav_tabs.find("#" + first_ladder_element_inset_id).html();
Try the following to fix your code:
btn.on('click',function(){
var ladder_nav_tabs = $('#tabs_nav'),
first_ladder_element_inset_id = ladder_nav_tabs.find('li').first().attr('id'),
first_ladder_element_inset_html = ladder_nav_tabs.find("#" + first_ladder_element_inset_id).html();
console.log(first_ladder_element_inset_html);
});
DEMO - Updating to valid id selector syntax
Alternatively you could shorten your code using jQuery's eq, similar to this:
btn.on('click',function(){
var theHtml = $('#tabs_nav li').eq(0).html();
console.log(theHTML);
});
Don't use jQuery purely as a selector engine:
btn.onclick = function() {
console.log(document.getElementById('tabs_nav').children[0].innerHTML);
};
Check out the jQuery first-child selector. Specifically:
btn.on('click',function(){
var first_child = $('#tabs_nav li:first-child');
var first_child_html = first_child.html();
});
Try this:
btn.on('click',function(){
var ladder_nav_tabs = $('#tabs_nav'),
first_ladder_element_inset_id = ladder_nav_tabs.find('li:first-child').attr('id'),
first_ladder_element_inset_html = ladder_nav_tabs.find(first_ladder_element_inset_id).html();
console.log(first_ladder_element_inset_html);
});
You have tou use :first-child
I am trying to find a way to use jQuery to get the first empty div with a certain class. I tried this:
$(".box[html='']").
but it didn't work. Is there an easy way to do this?
That syntax only works for attributes. For HTML contents, you can use .filter():
$('.box').filter(function () {
return $.trim($(this).html()) === '';
}).eq(0);
Edit: The problem with :empty is that line-breaks and spaces are not empty. So:
<div> </div>
<div>
</div>
... won't match.
This should work:
$('.box:empty:first')
http://api.jquery.com/empty-selector/
How about this:
You html:
<div class="empty"></div>
<div class="empty"></div>
your script:
$(document).ready(function(){
$(".empty:empty:first").html("JJJJ");
});
Check this
http://jsfiddle.net/y4Ef2/
var boxEq;
$('div.box').each(function(i,obj){
if (boxEq === void(0)) {
if ($(obj).html() === '') {
boxEq = i;
break;
}
}
});
// this is your div
$('div.box').eq(boxEq);
Try this one:
$('.box').each(function(){
if($(this).text().length == 0)
//box is empty
});
$("div.box:empty").eq(0)
added .eq(0) since you said first empty