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> ')
Related
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>
I am trying to figure out how to display number a right and efficient way for later calculation in HTML. This is what i can think of right now but doesn't seems right.
<p class = "price"> <span class ="sign">$</span> 10 </p>
Later implementation includes
$("p.price") * (the desire currency rate being called)
It then updates the whole page with the p.price
Consider using data attributes:
<p class="price" data-usd-price="10"> any markup you want </p>
You can then format it however you like and access the raw value later with:
$("p.price").data("usd-price")
Here a bit more complicated example:
<p class="price" data-usd-price="10">foo<span class="converted"></span></p>
<p class="price" data-usd-price="30">bar<span class="converted"></span></p>
<p class="price" data-usd-price="49.99">buzz<span class="converted"></span></p>
<p class="price" data-usd-price="99.99"><span class="converted"></span></p>
$('p.price').each(function () {
$(this)
.children('span.converted')
.html(
$(this).data('usd-price') * 22
)
})
The selector $("p.price") will give you an array of all paragraph elements with the class price. So your first issue is that you need to be aware of that, and your current multiplication code is not.
Second, you're trying to multiply the elements rather than the value of the one element.
Third, the value will be a string and you need a number.
I'd try something like:
<p class="price"><span>$</span><span class="amount">10</span>
Then your JS could look like this (minus smart error checking and optimization and such)
var amount = parseFloat($("span.amount:first").text(), 10);
$("span.amount:first").text(amount * exchangeRate);
Try to loop through paragraph children and check, if nodeName of the children is text then parse it's wholeText
var pContent = $('.price')[0].childNodes,
elem, num;
$.each(pContent, function (i, e) {
elem = $(e)[0];
if (elem && elem.nodeName == "#text") {
num = parseInt(elem.wholeText);
}
})
console.log(num)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<p class = "price"> <span class ="sign">$</span> 10</p>
when the page load the span is left empty but i want it to be shown (GBP as the base)
Simply change the spans text on window load instead of onchange event
var selectedIndex = select.selectedIndex;
$('.sign').text(prefix[selectedIndex ]);
$('.converted').text(currency[selectedIndex ] * $(price).data('price'));
Also i have some notes, if you have just one element you don't need to implement each function , and you don't need to make loop on each change as selectedIndex will filter the option which has selected attribute. http://jsfiddle.net/whoq9zd0/2/
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'm trying to match a span element with a certain class name and everything that comes between its start and finish.
My regex is /<\/?(span)[^>]*"myClass".*?<\/span>/gi. It works on <span class="myClass">...</span>, but it fails on something like below, only extending to the first </span>:
<span class="myClass"> ... <span class="anything else"> ... </span> ... </span>
How can I match it all from beginning to end?
This regex should do the job for you:
/span\s(?:class="myClass")>(.*)<\/span\>/
var txt = '<span class="myClass"><span class="anything else"></span></span>';
txt.match(/span\s(?:class="myClass")>(.*)<\/span\>/)
Output
["span class="myClass"><span class="anything else"></span></span>", "<span class="anything else"></span>"]
var txt = '<span class="myClass">foobar</span>';
txt.match(/span\s(?:class="myClass")>(.*)<\/span\>/)
Output
["span class="myClass">foobar</span>", "foobar"]
It is bad practice to use regexp for parsing html. You can work with DOM instead. This should do that you want:
var value = document.getElementsByClassName("myClass")[0].innerHTML;
you dont need REGEX only Jquery Find
suppose that we will ad a div
<div id="myid"><span class="myClass"> ... <span class="anything else"> ... </span> ... </span></div>
spanList = $('myid').find('.myClass, .anything else');
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