I'm not able to change HTML in jQuery - javascript

I need to change HTML code in jQuery, currently my HTML code looks like this:
<div class="intro-lead-in"><span>Creating quality Foods, Since 1940</span></div>
Expecting HTML code like below using jQuery:
<div class="intro-lead-in"><span>Creating quality Foods,<span class="class-name">Since 1940</span></span></div>
How can I accomplish this using jQuery?

I'm not sure about how do you determine what class names to put and where to split spans, but I'm assuming you wanna do it on commas.
Assuming a container of class intro-lead-in:
First, setup what classes do you want for each text fragment. I'm supposing from your exemple:
fragmentClassBindings = ['', 'class-name']
Then, do the actual replacing...
fragments = $('.intro-lead-in').html().split(',')
fragments.forEach(fragment => {
full = $('.into-lead-in').html()
cls = fragmentClassBindings[fragments.indexOf(fragment)]
$('.intro-lead-in').html(full.replace(fragment, `<span class="${cls}">${fragment}</span>`))
})
However, too much things are assumed here, you really need more explanation in your question. What are you trying to accomplish? What logic leads to the exemple you've provided?

Related

Issues replacing dashes by <br> with javascript using wordpress

I am trying to replace all dashes(-) by a "br" but it gives me issues.
I have tried
var strNewString = $('.member__designation').html().replace(/-/g,'<br>');
$('.member__designation').html(strNewString);
Here is the html
Before applying the code above
After applying the code above
You likely want
$('.member__designation').each(function() {
this.textContent = this.textContent.replace(/-/g,'<br>')
})
assuming $('.member__designation') only has text and not html
IF there is only SIMPLE HTML like <b> then do
$('.member__designation').each(function() {
this.innerHTML = this.innerHTML.replace(/-/g,'<br>')
})
It looks like you grab all elements with class .member__designation and you replace them with whatever your regex grabs. I think you must change your implementation

Extract div data from HTML raw DIV text via JS

I'm trying to extract data from a JS function that only renders an element's HTML - and I need the element's ID or class.
Example:
JS Element Value:
x = '<div class="active introjs-showElement introjs-relativePosition" id="myId">Toate (75)</div>';
I need to do get the element's id or class (in this case the id would be myId).
Is there any way to do this? Strip the tags or extract the text via strstr?
Thank you
The easiest thing to do would be to grab the jQuery object of the string you have:
$(x);
Now you have access to all the jQuery extensions on it to allow you to get/set what you need:
$(x).attr('id'); // == 'myId'
NOTE: This is obviously based on the assumption you have jQuery to use. If you don't, then the second part of my answer is - get jQuery, it's designed to make operations like these very easy and tackle compatibility issues where it can too
You may want to take a look at this:
var div = document.createElement('div');
div.innerHTML = '<div class="active introjs-showElement introjs-relativePosition" id="myId">Toate (75)</div>';
console.log(div.firstChild.className);
console.log(div.firstChild.id);

JSF Set CSS Style Using Javascript?

I have been looking with no success to see if I can dynamically apply a css style to JSF component or div using javascript. Is this possible.
This is pseudo code
<div style="myJSStyleFunction("#{myBean.value}")"> stuff </div>
And the function would return something like "position:relative;left:25px;"
I've had no luck and maybe it can't be done but would like a second opinion.
Edit:
I'm trying to see if I can keep a separation / reduce the coupling between the presentation/view and the model/controller. This is for indenting commenting or product reviews (to nest replies to comments or reviews). The most I really want to track is an integer on how deep a reply is. First level = 0 second level = 1, and so on. So a comment or product review would be 0 deep, a reply to the comment or review would be 1 and so on.
Then in the EL I wanted to call a javascript function and do something like
<script>
myJSStyleFunction(depth){
if(depth<=5){
var nest=20*depth;
var style="position:relative;left:" + nest + "px;";
return style;
}
}
</script>
And then then say for a third level comment (a reply to a reply) it would look like this:
<div style="position:relative;left:40px;"> stuff </div>
where
#{myBean.value}
evaluates to 2
I suspect like Daniel says I'll have to tightly couple the view but I'd rather not have to. I'd think there has to be a way. But maybe not.
I don't know where there are cleaner solutions for this. However this is one suggestion.
Assume your page looks like below and myBean.getValue() method returns an integer.
<h:form id="frm">
<div style="#{myBean.value}"> div1 </div>
<div style="#{myBean.value}"> div2 </div>
</h:form>
So you can do something like this at 'window.onload'.
<head>
<script>
window.onload = function() {
var childList = document.forms['frm'].childNodes;
for(var i = 0; i < childList.length; i++) {
if(childList[i].nodeName == 'DIV') {
var _div = childList[i];
var depth = _div.getAttribute('style');
_div.setAttribute('style', 'position:relative;left:' +(depth *20)+ 'px;');
}
}
}
</script>
</head>
Note: 1. In above sample code I assume all the DIVs inside the form should be indented.
2. For IE you may need to use _div.style.setAttribute('cssText','position:relative;left:' +(depth *20)+ 'px;')
3. Another solution for your question is using <script> tags immediately after your divs and putting the js part inside them. In this way you don't have to use fake styling style="#{myBean.value}" or window.onload event because you can directly call #{myBean.value} in your script.
I decided to skip the javascript approach and settled on a simpler and I think cleaner method to create the dynamic css classes for my situation. I already capture/calculate the depth value for each comment when it is entered. So I am just returning that value in EL and concatenating it to a 'base name' for the css class like so:
<div class="indent_#{(comment.commentDepth le 5) ? comment.commentDepth : 5}" >
comment comment blah blah blah
</div>
"indent_" is the base name for the css class. So for a 0 level comment it will have a class="indent_0". A reply to that comment will have class="indent_1".
I use the ternary so that if there are lot of replies under a given comment it doesn't indent right off the right hand side of the page. Even though you can keep going deeper, it will only indent up to 5 levels.
For my case at the moment, this is a simpler and cleaner method of adding some dynamically generated css class names. Right now I have to define 6 classes for this in the css file, but perhaps I'll figure out how to nest the boxes but it isn't a priority this works just fine for me for now.

extracting text from html file

I'm trying to get nodes containing text from html file using Javascript and jQuery.
if I have a node like
`
<div>txt0
<span>txt1</span>
txt2
</div>
How can I select elements that meets this criteria??
Meaning, I need to retrieve thedivand thespan` , and it would be even better to know location of the text.
I'm trying to get the text to replace it with images in a later function.
I tried this
`
$('*').each(function(indx, elm){
var txt = $(elm).text();
// my code to replace text with images here
});
`
but it does not get the required results.. it does all the parsing in the first element, and changes the html totally.
I don't know exactly what you're trying to solve, but perhaps you can be a bit more specific with your selector?
$("div span").text(); // returns 'txt1'
$("div").text(); // returns 'txt0txt1txt2'
By adding ids and/or classes to your html, you can be very specific:
<div class="name">Aidan <span class="middlename">Geoffrey</span> Fraser</div>
...
// returns all spans with class
// "middlename" inside divs with class "name"
$("div.name span.middlename").text();
// returns the first span with class
// "middlename" inside the fourth div
// with class "name"
$("div.name[3] span.middlename[0]").text();
JQuery has pretty good documentation of these selectors.
If this doesn't help, consider explaining the problem you're trying to solve.
Your markup structure is a bit uneasy. Consider changing to something like this
<div>
<span>txt0</span>
<span>txt1</span>
<span>txt2</span>
</div>
Then using jQuery
$("div span").each(function(k,v) {
$(this).html("<img src=\""+v+".jpg\" />"); //replace with the image
});

Count Upwards for ID jQuery

I have the following HTML structure
<div id="test-1-yay"></div>
... bunch of code ...
<div id="test-2-yay"></div>
... bunch of code ...
<div id="test-3-yay"></div>
I was wondering how I can use jQuery to basically identify each of these "id's" and then apply some jQuery to them ? I'm new to this so little unsure ? Something like
if $('#test-1-yay' || '#test-2-yay' || '#test-3-yay') {
do stuff to all ID's
}
But the prob is I want this to continue as it could go to #test-201-yay, #test-202-yay etc ?
Thx
Why don't you add a class to the divs?
You could try something like:
$("div[id^='test']")
or
$("div[id$='yay']")
or try to combine the two
Manual
You could use a substring selector to get most of the way there:
var divs = $('div[id^=test-]'); // All divs with IDs starting with "test-"
...which would work better if you changed the naming convention a bit so the number was at the end. But I think I'd lean toward using some other aspect of the structure (the parent node), or a class, or a data-xyz attribute...
Edit A pair of substring selectors can do it:
var divs = $('div[id^=test-]').filter("div[id$=yay]");
That gets all of the ones whose IDs start with "test-" and then filters out the ones that don't end with "yay". Close, anyway...
you could do it like that:
$("div[id^=test-]").each(function(){ //selects all dives having the string 'test-' in it
$that = $(this)
$that.text($that.attr("id").split("-")[1]) //splits the sting by "-" and gives you out the middle part (in your case the number)
})
test it here http://jsfiddle.net/aj5Qk/1/

Categories

Resources