I need to remove the text 'at' from this title.
<p>Marge Makes Pancakes Email at</p>
The text in this title is dynamically created so I can't change the whole thing.
I tried using this but it doesn't work.
<script>var elements=document.getElementsByClassName("spotlight__title");elements[0].innerHTML=elements[0].innerHTML.replace(/at/g,"");</script>
You need to iterate over collection returned from getElementsByClassName.
var elements = document.getElementsByClassName("spotlight__title");
Array.from(elements).forEach( element =>
element.innerHTML = element.innerHTML.replace(/at/g,"")
)
You can use querySelectorAll to find all elements by using a CSS Selector and then iterate over them to replace text according to your regex.
function replaceText(target, re, newText) {
document.querySelectorAll(target).forEach(function(element) {
element.textContent = element.textContent.replace(re, newText).trim();
});
}
replaceText('.spotlight__title', /at$/g, '');
<p>
Marge Makes Pancakes Email 1 at
</p>
<p>
Marge Makes Pancakes Email 2 at
</p>
<p>
Marge Makes Pancakes Email 3 at
</p>
Related
Used below HTML & JS to get first character of string and display. Manually its possible to calculate and get value.
When its goes to dynamic and name with only first and last name not sure how to calculate character position after space and get first character of word.
$('.splitname .fname').html(name.charAt(0));
$('.splitname .mname').html(name.charAt(8));
$('.splitname .lname').html(name.charAt(16));
<div class="name">Desmond Patrick Reymond</div>
<div class="splitname">
<span class="fname">D</span>
<span class="mname">P</span>
<span class="lname">R</span>
</div>
Use this logic:
"Desmond Patrick Reymond".split(" ").map(name => name[0])
// => ["D", "P", "R"]
If you need to modify the HTML programmatically, do:
let s = $('.name').text();
s.split(" ").map(name => $('.splitname').append(name[0]))
(It's not really good practice to use map for side effects though; you may choose to use forEach instead.)
You can simply use match() function and a simple ReGex to get the dynamic text data with spaces without having to check for charAt()
//get text
let name = $('.name').text();
//match the spaces
var matches = name.match(/\b(\w)/g); // [D,P,R]
//join the chars - if needed
var joinChar = matches.join(''); // DPR
//show the split name
$('.splitname').text(joinChar);
console.log(matches ) // [D,P,R] //Array
console.log(joinChar) //DPR //String
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">Desmond Patrick Reymond</div>
<div class="splitname"></div>
You can make use of Array#split and Array#map and Array#join as in the demo below. Result will be:
<div class="splitname">
<span class="fname">D</span>
<span class="mname">P</span>
<span class="lname">R</span>
</div>
//Classes for the initials
const classes = ['fname', 'mname', 'lname'];
//Where to put the initials
$('.splitname')
//make HTML generated content of
.html(
//Get Full Name
$('.name').text()
//Break into names array
.split(' ')
//Get initial of each name
.map(name => name.charAt(0))
//Wrap each initial in a span element
.map((initial,index) => `<span class="${classes[index]}">${initial}</span>`)
//Join all span elements array into string
.join('')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">Desmond Patrick Reymond</div>
<div class="splitname"></div>
How to find out the element which does not contain any class?
<p>You will receive the ebook in your email</p>
<p class="active">You will NOT receive the ebook in your email</p>
I want to find the paragraph element which does not contain any class.
Sample code is much appreciated.
Keep Coding...
You can use the :not() pseudo class:
let matches = document.querySelectorAll('p:not([class])');
for (let p of matches) {
console.log(p.textContent);
}
<p>You will receive the ebook in your email</p>
<p class="active">You will NOT receive the ebook in your email</p>
If you want to also match elements that have the class attribute, but which is still empty, then add that in the selector: p:not([class]), p[class=""]. Of course, you can then also think of a class attribute that has just space(s), ...etc.
You could filter your paragraphs by the length of their classList
var allParagraphs = Array.from(document.querySelectorAll("p")).filter(({classList}) => classList.length === 0)
console.log(allParagraphs)
//for older browsers
var allP = [];
document.querySelectorAll("p").forEach(function(el) {
if(el.classList.length === 0) allP.push(el);
})
console.log(allP);
<p>no class</p>
<p>nope</p>
<p class="df">öldskjf</p>
<p class="ölsdf">slkdf </p>
I am having a trouble for fetching innerHTML of the following two strong tags
<div>
<strong>data 1</strong>
<span class="and">and</span>
<strong>data 2 </strong>
</div>
<div>
<strong>data 3</strong>
<span class="and">and</span>
<strong>data 4 </strong>
</div>
i want to get data1, data2 in console but i'm unable to achieve anything.
I have tried document.querySelector("strong") but it just provide me data1.
How can i fetch data2 data3 & data4 from other strong tag?
Any help is appreciated.
i know i can do
document.getElementsByTagName("strong")['increment_operator'].innerHTML;
and
document.querySelectorAll("strong");
querySelector finds the first result and stop searching whereas querySelectorAll finds all.
Try code below to log html of strong tag:
var elems = document.getElementsByTagName('strong');
for (i=0;i < elems.length;i++{
console.log(elems[i].innerHTML)
}
To get innerHTML of the last strong tag in html run code below:
var elems = document.getElementsByTagName('strong')[:1];
console.log(elems[elems.length-1].innerHTML);
If you have same tag and you want specific tag innerHTML then give unique ids and then try to fetch or if you want to fetch all strong tag innerhtml then use queryselectorall()
As example
<div>
<strong>data 1</strong>
<span class="and">and</span>
<strong>data 2 </strong>
</div>
<div>
<strong>data 3</strong>
<span class="and">and</span>
<strong>data 4 </strong>
</div>
var a = document.querySelectorAll("strong");
for (var i = 0; i < a.length; i++) {
alert(a[i].innerHTML);
}
Summing up the partials:
The document.querySelector(commaSeperatedStringOfSelectors) only finds the first node in the documentsatisfying the selectors it is given. So you need to be more specific with it, need to supply some queryable selectors to your html elements, like id class.
But if you want to select more widely follow:
document.querySelectorAll(commaSeperatedStringOfSelectors) to get an array of all the nodes satisfying the selectors. Then you can select the element you need by index. fiddle
Or you need to use #Andriy Ivaneyko's answer style, use getElementByTagName('tagname'), getElementsByClassName('class'), or getElementById('id').
Note: document.querySelectorAll(commaSeperatedStringOfSelectors) is more versatile, it gives you opportunity to be both more specific or more unspecific. You can use a string like that in it: 'strong, div.animals, a'.
Ok i did my job by doing following.
var divLength = document.getElementsByTagName("div").length;
var z = 0;
for(i=0; i<divLength; i++){
var dataFromFirstStrong = document.getElementsByTagName("strong")[z].innerHTML;
z++;
var dataFromSecondStrong = document.getElementsByTagName("strong")[z].innerHTML;
z++;
}
i need to split an HTML element based on a users selection like this :
<p> Hi , i need to <b>split <i> an [HTML] element </i> based on a users selection </b></p>
in first use :
<p> Hi , i need to <b>split <i> an </i> HTML <i> element </i> based on a users selection </b></p>
and in 2nd use :
<p> Hi , i need to <b>split <i> an </i></b></p>
HTML
<p><b><i> element </i> based on a users selection </b></p>
i have getSelectionHtml() , replaceSelectionWithHtml(html) from here .
also :
function range(){
var range = window.getSelection().getRangeAt(0);
var a = range.startContainer ;
els = [];
while (a.tagName != 'DIV') {
els.unshift(a);
a = a.parentNode;
}
}
//so i have els[0] = <p> element , els[1] = <b> element , els[2] = <i> element
please help .
If you just want replace the particular string. You can try this.
("<p> Hi , i need to <b>split <i> an [HTML] element </i> based on a users selection </b></p>").replace(/[HTML]/g, '</i> HTML <i> ')
I have an unordered list called test
<ul id='test'></ul>
it is dynamically populated with data via ajax. Each item 'li' is a div containing 'p' paragraphs. Each paragraph contains some information.
Ex:
<li> <div> <p> test </p> </div> </li>
<li> <div> <p> hi how is it going?</p> </div> </li>
<li> <div> <p> not a test</p> </div> </li>
<li> <div> <p> whoa</p> </div> </li>
I also have a search box which i can get a search term from, I use:
var searchTerm = $("#search").val().trim().split(' '); // an array of words searched for
What I am trying to do is find a way to select all 'li' elements which contain all or some of the search words, but I'm not sure how to approach it best.
Currently, I am doing this:
var results = $('p:contains("'+ searchTerm[0] +'")');
to get an exact match on the first term, but I want to search for multiple terms, not just one.
I would want to search for 'test hi' and get back three nodes cause it searches for 'test' and 'hi'.
I also thought of:
var results2 = $('p').filter(function( index ) {
return ( this +':contains("'+ searchTerm +'")' );
});
Anyone point me in the right direction?
You could do some black magic with the selector, like this:
var results = $('p:contains("' + searchTerm.join('"), p:contains("') + '")');
This looks hard, but I'll explain it.
It joins the search terms with "), p:contains(". Then it just adds the missing p:contains(" and ") to the ends of the result string and searches for it.
A combination of $.filter and $.each (or array.forEach, if you don't care about ie8) can also be of use here:
var searchTerms = ["how", "test"];
$('div').filter(function () {
$text = $(this).text();
var found = 0;
$.each(searchTerms, function (index, term) {
found = $text.indexOf(term) > -1 ? found +1 : found;
})
return found;
}).addClass('match');
jsFiddle