How do get contents of a p element one at a time - javascript

Using jQuery, I need to parse the contents of each <p> tag individually and then replace the text with the new text.
The code at the moment looks like:
str = $('p').text();
str = str.replace('yadayada','yada');
$('p').text(str);
This is currently getting the contents of all the <p> tags, concatenating them then replacing the massive block of text into each <p> which is close but not quite what I'd like it to do.
Is there a way to get the contents of each <p> block one at a time and replacing it with only it's contents? I do not know what ids or classes are being applied to them hence the need to use the generic tag.
Any help is much appreciated! :)

Use the text(fn)
A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.
$('p').text(function(_ text){
return text.replace('yadayada','yada');
});

Use the text() version that accepts a callback as the second argument and return the replaced content from the callback
$('p').text(function(i, str) {
return str.replace('yadayada', 'yada');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>yadayada-1</p>
<p>yadayada-2</p>
<p>yadayada-3</p>
<p>4</p>

You can use .each method on the colletion:
$('p').each(function (pEl) {
var text = pEl.textContent;
});

Related

Regex in javascript replace function

Am newbie to regex am trying to do some regex replace function in java script here is my content and code
jQuery("td[headers='name_head']").each(function (index, value) {
var text = jQuery(this).html();
if( text.indexOf('<a href=') >= 0){
jQuery(this).text(text.replace(/<a href=.*\"$/, ""));
}
});
Html content will be look like this
Calculate Points
i just want to remove only the value inside href ""
Please throw some light on this
Regards
Sathish
The text() method just retrieves the text contents which doesn't include any HTML tags. You can use html() method with a callback function where you can get the old HTML content as the second argument to the callback and based on the old value generate updated HTML.
The better way is to update the href attribute value of a tag to empty by directly selecting them, there is no need to loop over them since all values need to be empty.
jQuery("td[headers='name_head'] a").attr('href', '');
UPDATE 1 : In case you want to iterate and do some operation based on condition then do something like this.
jQuery("td[headers='name_head'] a").each(function(){
if(//your ondition){
$(this).attr('href', '');
}
});
or
jQuery("td[headers='name_head']").each(function(){
if(//your ondition){
$('a', this).attr('href', '');
}
});
UPDATE 2 : If you want to remove the entire attribute then use removeAttr('href') method which removes the entire attribute itself.
jQuery("td[headers='name_head'] a").removeAttr('href');
Why would you reinvent the wheel?
You don't need regex to achieve this, you can simply do it this way:
jQuery("td[headers='name_head'] a").attr('href', '');
It will set href to "" for all <a> elements inside td[headers='name_head'] so it will always respect your condition.
I haven't tested this code; but something like this should help, don't think you need to use regex for this;
$('a.DisableItemLink[href!=''][href]').each(function(){
var href = $(this).attr('href');
// do something with href
})
This piece of code selects all elements which have the class DisableItemLink with a location set and sets it to blank.
I am curious as to what you are trying to do in the larger scheme of things though, sounds like there might be better ways to go about it.
Reference: some good selector combinations for links

Check for existence any string inside html element with jQuery

I'm aware you can do something like this:
$('.document-content p:has(br)').next('p').addClass("newClass")
to check whether a p tag has a br tag inside:
<p>
<br>
</p>
How to check if there's also for the existence of ANY string inside?
<p>
"Some text"
<br>
</p>
(The reason is, I want to remove all br inside the p tags that have a string inside.)
You can use the :contains selector:
$('.document-content contains("some text")').next('p').addClass("newClass")
If the string to find is stored in a variable you would need to concatenate it in the selector:
var searchString = 'some text';
$('.document-content contains("' + searchString + '")').next('p').addClass("newClass")
The reason is, I want to remove all br inside the p tags that have a string inside.
In this case you can get the text() of the element and overwrite the html() with it:
$('.document-content').html(function() {
return $(this).text();
});
Or
$('.document-content').html($('.document-content').text());
Both the above will work, the latter is shorter but (IMO) uglier and makes another DOM request.
Example fiddle
You can do something like thi https://jsfiddle.net/joL9xh2r/
$('p').each(function(i,ele){
if($(ele).text().replace(/\s/g, '').length>0)
{
alert($(ele).attr('id')+' has string');
}
})
Here are two paragraphs , one with string inside, and one without text, you can check if the paragraph contains a string using text(), Now you can do whatever you want within the if condition, its only true whan there is a string inside the p element
Now if you want to removethe br tag , then you can do this,
https://jsfiddle.net/joL9xh2r/1/
$(ele).html($(ele).text())
But, Remember this will remove all the html tags inside, for Example https://jsfiddle.net/joL9xh2r/2/,
here you have
<p id='x'>
"Some text"
<br/>
<b>abc</b>
</p>
A bold tag within p , so the above solution, and the one suggested by rorry will remove the b tag as well.
The best way to remove only br this would be
https://jsfiddle.net/joL9xh2r/3/
$('p').each(function(i,ele){
if($(ele).text().replace(/\s/g, '').length>0)
{
alert($(ele).attr('id')+' has string');
$(ele).find('br').remove();
}
})

jQuery "add" Only Evaluated When "appendTo" Called

this has been driving me crazy since yesterday afternoon. I am trying to concatenate two bodies of selected HTML using jQuery's "add" method. I am obviously missing something fundamental. Here's some sample code that illustrated the problem:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<p id="para1">This is a test.</p>
<p id="para2">This is also a test.</p>
<script>
var para1 = $("#para1").clone();
var para2 = $("#para2").clone();
var para3 = para1.add(para2);
alert("Joined para: " + para3.html());
para3.appendTo('body');
</script>
</body>
</html>
I need to do some more manipulation to "para3" before the append, but the alert above displays only the contents of "para1." However, the "appendTo appends the correct, "added" content of para1 and para2 (which subsequently appears on the page).
Any ideas what's going on here?
As per the $.add,
Create a new jQuery object with elements added to the set of matched elements.
Thus, after the add, $para3 represents a jQuery result set of two elements ~> [$para1, $para2]. Then, per $.html,
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
So the HTML content of the first item in the jQuery result ($para1) is returned and subsequent elements (including $para2) are ignored. This behavior is consistent across jQuery "value reading" functions.
Reading $.appendTo will explain how it works differently from $.html.
A simple map and array-concat can be used to get the HTML of "all items in the result set":
$.map($para3, function (e) { return $(e).html() }).join("")
Array.prototype.map.call($para3, function (e) { return $(e).html() }).join("")
Or in this case, just:
$para1.html() + $para2.html()
Another approach would be to get the inner HTML of a parent Element, after the children have been added.

Javascript to replace a string inside a tag

<nav class="woocommerce-breadcrumb">Home > Product</nav>
Using jQuery or Javascript how would I be able to rename the word 'Product' to some other value?
var brandname = $('.tax-product_brand h1.page-title').text();
var crumb = $('.woocommerce-breadcrumb').text();
console.log(crumb);
crumb.replace("Product", brandname);
I tried the above with no luck
Use .html() rather than .text() or else you'll lose your markup:
var crumb = $('.woocommerce-breadcrumb').html();
Then apply the value back to the element:
$('.woocommerce-breadcrumb').html(crumb.replace("Product", brandname));
Alternatively, a much easier way would be to put "Product" in its own element, and then just replace that element's text:
<nav class="woocommerce-breadcrumb">Home > <span class="item">Product</span></nav>
Then your jQuery would simply be:
$(".woocommerce-breadcrumb .item").text(brandname);
You then need to insert your string into the DOM. As it is, you're just doing a string operation and discarding the return value.
$('.woocommerce-breadcrumb').text(crumb.replace("Product", brandname));
EDIT: As mentioned in a comment, you should use .html() instead of .text(). .text() will strip all of your HTML, i.e. your <a> tag.
.replace returns a new string, so you have to set the text of crumb with the returned string.
Its replaced Here is demo.
var brandname = 'My Name';
var crumb = 'My Product';
console.log(crumb);
var d= crumb.replace("Product", brandname);
alert(d);
var brandname = $('.tax-product_brand h1.page-title').text();
$(".woocommerce-breadcrumb:contains('Product')").html(function(_, html) {
return html.replace(/(Product)/g, '<span>'+brandname+'</span>')
});
I was able to use the above to gain what I wanted whilst keeping the formatting of the a tag
Avoid using free text. This will increase processing overhead, when you'll do DOM calculations.
It is good, if you can use tag to display the end product/page name.
The html will look like:
<nav class="woocommerce-breadcrumb">
<a href="http://domain.com/" class="home">
Home
</a>
<span class="currentPage">>Product</span>
</nav>
Now, you can use simple DOM operation to change the text() of expected element.
var currentPage=$(".currentPage");
$(currentPage).text('> NewText');

Add actual HTML elements to PRE/CODE contents

I'm trying to create a quick/dirty way to add some syntax highlighting for pre/code tags in html using javascript.
The problem i'm running into, is that if i edit either the text() or html(), I get escaped content. That is, the added tags render as pre/code, or i get a bunch of eascape characters.
Consider the following html:
<pre>
<code class="target">
public interface __iIFoo { }
public class __tBar : __iIFoo { }
var list = new List__/__iIFoo\__();
</code>
</pre>
The goal here is to replace occurrences of __iIFoo with:
<span class="interface">IFoo</span>
So that it can be highlighted with css. And of course, when it's rendered, I don't want to see the actual SPAN tag.
Here's what I've tried:
$(function(){
var iPatt = /__i\w+/g
$.each($(".target").text().match(iPatt), function(i,match){
var replace = '<span class="interface">'+match.substring(3)+'</span>';
$(".target").text(function(){
return $(this).text().replace(match, replace);
});
});
});
This works, BUT, the span tags I'm adding show up in the rendered content e.g. they are just like all the other pre code. I don't want to see it!
Use .html() instead of .text(). When you use .text(), the value is the literal text that you want users to see, so it replaces special HTML characters with entities so they'll show up literally.
DEMO
.text() treats value as text and .html() render it as html content
$(".target").html(function () { //replace text with html
return $(this).text().replace(match, replace);
});
Try using it with html instead:
$(function(){
var iPatt = /__i\w+/g
$.each($(".target").text().match(iPatt), function(i,match){
var replace = '<span class="interface">'+match.substring(3)+'</span>';
$(".target").html(function(){
return $(this).text().replace(match, replace);
});
});
});
As I said in my comment, change the html rather than the text (fiddle).
As a side-note, it's worrisome that you're completely overwriting the contents of .target every time you encounter a match. You should take advantage of RegExp capture groups and perform only one assignment.
(function () {
var iPattern = /__i(\w+)/g,
iTemplate = "<span class='interface'>$1</span>";
$(".target").each(function () {
this.innerHTML = this.innerHTML.replace(iPattern, iTemplate);
});
})();

Categories

Resources