Is there a way to apply css to part of the element? - javascript

I am looking for a way to apply new CSS to only part of the element.
For example. The original HTML looks like
<p>123456</p>
I want to make only 456 into bold.
Of course, I can do it by adding another tag into 456 like
<p>123<b>456</b></p>
But in my application, I do want not to change the original DOM structure. By adding a new tag, I changed the DOM structure.
To do that, I am thinking of adding new custom attribute to the existing tag like
<p data-wms="e-3">123456</p>
Here data-wms means that there are special part and e-3 means that from index 3 character (it is 4 here) to the end will have a special attribute (like bold in this example)
Now I have all the information about where to change inside the element.
But still, how can I do that with javascript without adding a tag, without changing dom.
Thanks

You can use the span element to do so, it's made specifically to handle inline styling while mantaining the overall structure.
An example would be:
<p>123<span class="bold-highlight">456</span></p>

Thanks to everyone's advice, I researched more, especially about nth-letter.
Though nth-letter is exactly what I want, I found that it is still just proposal, not implemented in any browser.
Thus, there is no way to applying different css letter by letter in one text element without embracing each letter with span tag at this moment (2021-March). I hope that there will be nth-letter in the near future.
I think that I have to re-design my project...

if it's a static page and you want to change a style for specific text in a specific tag like the following case
<p>11111</p>
<p>22222</p>
<p>33333</p>
<p>44444</p>
let's say you want just style the third element, you can change it by the following code using jQuery for sure you can use JavaScript but jQuery will help you to make your code shorter
$( "p:nth-child(3)" ).css("color","#f00");

Related

Best practice in finding a DOM element

I want to toggle(hide/show) an element when a button is being pressed. I have two ways as to implement this:
Find the element according to its class name, e.g $('.my-content')
Find the element according to its relevant DOM position towards the button, e.g. $('#my-button').parent().next().next().next()
However, none of the above seems to me very reliable since in case someone changes the HTML code, the above approaches should not work. Is there something more reliable I am missing?
If it's a specific element, supply it with an Id value and use that
to find it.
If it's a TYPE of element, use a class name.
Other than that, there's no real conventions. Just try and make sure that somebody reading your code understands what is going on.
A very good practice is to decouple HTML, CSS and JS.
When binding javascript to DOM elements you should use javascript selectors.
Basically classes with some custom prefix (like js-) which will be used only for javascript purposes (not css style).
So whenever the DOM tree structure or the CSS class names are changed, you can still have your working JS selector
HTML
<div class="my-content js-toggle-element"></div>
JS
$('.js-toggle-element')
CSS
.my-content{ ... }
Plus, using Javascript Selectors:
makes HTML highly readable: you can easily find out what will happen to that element with that js class
allows you to easily apply/disapply that behaviour also to other elements in the future, simply by adding/removing that class in your HTML and without affecting CSS at all
<div class="my-content js-toggle-element"></div>
...
<div class="another-content-to-toggle js-toggle-element"></div>
Using jQuery will be much easiest way. Like this -
$( ".target" ).toggle();
The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property. If the element is initially displayed, it will be hidden; if hidden, it will be shown.
Reference - jQuery Toggle
If the class or the position of the element in DOM is changing then you can try
selecting it with the inner text
$("button:contains('buttontextgoeshere')")

Replace part of innerHTML without reloading embedded videos

I have a div with id #test that contains lots of html, including some youtube-embeds etc.
Somewhere in this div there is this text: "[test]"
I need to replace that text with "(works!)".
The normal way of doing this would of course be:
document.getElementById("test").innerHTML = document.getElementById("test").replace("[test]","(works!)");
But the problem is that if i do that the youtube-embeds will reload, which is not acceptable.
Is there a way to do this?
You will have to target the specific elements rather than the parent block. Since the DOM is changing the videos are repainted to the DOM.
Maybe TextNode (textContent) will help you, MSDN documentation IE9, other browsers also should support it
Change your page so that
[test]
becomes
<span id="replace-me">[test]</span>
now use the following js to find and change it
document.getElementById('replace-me').text = '(works!)';
If you need to change more than one place, then use a class instead of an id and use document.getElementsByClassName and iterate over the returned elements and change them one by one.
Alternatively, you can use jQuery and do it even simpler like this:
$('#replace-me').text('(works!)');
Now for this single replacement using jQuery is probably overkill, but if you need to change multiple places (by class name), jQuery would definitely come in handy :)

Setting an attribute to the last position

Is it possible to set a new attribute to the last position of a html element using javascript/jQuery?
This would be helpfull for me in a case where the attribute order is important to decide whether the paragraph has changed or not.
Example:
<p attribute1="true" attribute2="true">
Now, i would like to add a third attribute so that the resulting paragraph would look like
<p attribute1="true" attribute2="true" attribute3="true">
No, it's not possible. Attributes are unordered in HTML and XHTML markup languages, so browsers are free to return them in whatever order they like, e.g. alphabetic, specified, etc.
You should rethink your approach, for instance using the .data() method to track changes:
$("#el").data("changeHistory", []);
// ...
$("#el").data("changeHistory").push(new Date().toString());
Optimally you should never be in a position where you need to read attributes in order (by index).
If you have an element like so <div id="container">, you can add an attribute using jQuery like so $('#container').attr('disabled', true);. Keep in mind this should add the attribute to the end of the element.
Another tip is if you are looking to modify a DOM element attribute such as style, consider looking at the jQuery API to see what methods are avialable before writing anything too crude. For example, if you wanted to add a style you could simply do $('#container').addClass('hover');

Alternative for execCommand('underline');

Okay, some Guys will know what i mean and edit my Question but they did it wrong.
A better explanation:
You have a contenteditable div with the text This is a Test String..
If you use now the execCommand('underline') on Test String you get This is a <u>Test String</u>
if you use now the execCommand('strikethrough') on is a Test you get This <s>is a <u>Test</u></s><u>String</u>, THIS is correct.
So, in HTML5 <u> and <s> are obsolete.
For the first execCommand you can use the surroundContents() with a <span style="text-decoration:underline;">. If you now use the surroundContets() for the second execCommand you receive the BAD_BOUNDARYPOINTS_ERR.
The Thing i want is a Function which works like the execCommand in this case but with functions where i can define with witch HTML-Tag the String will wrapped… (It should be intelligent in the case if there is any overlapping…)
The surroundContents() will have problems: if the selection encompasses multiple block elements, such as <div>s or <p>s, the surrounded contents will be placed in a new block, breaking it out of its original position. To overcome this, you could easily adapt my answer here: apply style to range of text with javascript in uiwebview
You'll need to do the following:
Create a CSS class with the rule "text-decoration: underline;"
Add an intersectsNode method of Range for browsers that don't have it, such as Firefox (see MDC for an example: https://developer.mozilla.org/en/DOM/range.intersectsNode)
If you care about IE, you'll need to write a completely different solution.
CSS text-decoration: underline.

Complex jquery selection that also involves custom xml tags

I want to write a select something like...
#window_4 > content > p:eq(0)
I think I have this correct, but I have a few selectors that are all similar but I can't test them all at once.
Am I right in saying this is selecting an element, who is the fist p tag child of a content tag that is a child of a tag with id 'window_4'
If I have gotten this wrong, can you give me some pointers. Would love to be able to simplify this code, I have more code selecting the tag I am after then actually doing stuff with them.
Looks good to me, although you can make it a bit more readable by substituting p:eq(0) for p:first.
Edit for comment:
jQuery always returns an array of elements, no matter whether 0, 1 or many elements were found. On these elements, yes, you can perform JS functions, such as innerHTML. You can access each element returned by jQuery just as if you would any other array:
$(".red")[0].innerHTML = "Glen Crawford";
More info: http://groups.google.com/group/jquery-ui/browse_thread/thread/34551a757f139ae1/20111f82c2596426

Categories

Resources