- [Solved-6 Solutions] Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery — javascript tutorial
- Solution 1:
- Solution 2:
- Read Also
- Solution 3:
- Solution 4:
- Read Also
- Solution 5:
- Solution 6:
- UP NEXT IN Javascript
- Related Searches to Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery — javascript tutorial
- .after()
- .after( content [, content ] ) Returns: jQuery
- version added: 1.0 .after( content [, content ] )
- version added: 1.4 .after( function )
- version added: 1.10-and-2.0 .after( function-html )
- Passing a Function
- Additional Arguments
- Additional Notes:
- Examples:
- Изменяем псевдоэлемент :after с помощью jQuery
- Lorem ipsum dolor sit amet, consectetur adipiscing elit
- How to Select and Manipulate CSS pseudo-elements using jQuery
- The attr() Function
- The hover() Method
[Solved-6 Solutions] Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery — javascript tutorial
How to select and manipulate CSS pseudo-elements such as ::before and ::after using jQuery ?
For example, the stylesheet has the following rule:
How to change ‘wiki’ to ‘wikitechy’ using jQuery ?
Solution 1:
You can not select an element via pseudo-selector, but you can add a new rule to your stylesheet with javascript.
var addRule = function(sheet, selector, styles) < if (sheet.insertRule) return sheet.insertRule(selector + " ", sheet.cssRules.length); if (sheet.addRule) return sheet.addRule(selector, styles); >; addRule(document.styleSheets[0], "body:after", "content: 'wikitechy'");
Solution 2:
We could pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:
If we need to prevent the ‘other text’ from showing up, we could combine this with solution like this:
Read Also
Solution 3:
To manipulate CSS pseudo elements using the hover() function.
span.change:after Place cursor below.
wiki
Solution 4:
We can’t select pseudo elements in jQuery because they are not part of DOM. But we can add an specific class to the parent element and control its pseudo elements in CSS.
Read Also
Solution 5:
Solution 6:
Here is the way to access :after and :before style properties, defined in CSS:
// Get the color value of .element:before var color = window.getComputedStyle( document.querySelector('.element'), ':before' ).getPropertyValue('color'); // Get the content value of .element:before var content = window.getComputedStyle( document.querySelector('.element'), ':before' ).getPropertyValue('content');
UP NEXT IN Javascript
Related Searches to Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery — javascript tutorial
jquery get pseudo element jquery pseudo element click jquery change pseudo element css set pseudo-element properties with javascript jquery change before content javascript get pseudo element access the css after selector with jquery jquery pseudo selectorjquery ::after click event clickable pseudo elements jquery before click event before onclick jquery before click event javascript css after click event jquery modify pseudo elements css jquery after click event finish javascript tutorial java script javascript javascript array javascript book learn javascript javascript code javascript editor javascript class javascrip javascript debugger javascript online javascript examples javascript test javascript document javascript slider what is javascript javascript form validation javascript validator html javascript javascript alert javascript events javascript print javascript dom javascript object javascript function href javascript javascript date javascript prompt javascript onclick javascript return javascript for javascript number javascript confirm javascript onchange javascript regular expression javascript if javascript variable javascript timer javascript cookie javascript getelementbyid javascript innerhtml javascript call javascript regexp javascript includes javascript this javascript eval
- INTERVIEW TIPS
- Final Year Projects
- HR Interview Q&A
- GD Interview
- Resume Samples
- Engineering
- Aptitude
- Reasoning
- Company Questions
- Country wise visa
- Interview Dress Code CAREER GUIDANCE
- Entrance Exam
- Colleges
- Admission Alerts
- ScholarShip
- Education Loans
- Letters
- Learn Languages
World’s No 1 Animated self learning Website with Informative tutorials explaining the code and the choices behind it all.
.after()
.after( content [, content ] ) Returns: jQuery
Description: Insert content, specified by the parameter, after each element in the set of matched elements.
version added: 1.0 .after( content [, content ] )
HTML string, DOM element, text node, array of elements and text nodes, or jQuery object to insert after each element in the set of matched elements.
One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or jQuery objects to insert after each element in the set of matched elements.
version added: 1.4 .after( function )
A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.
version added: 1.10-and-2.0 .after( function-html )
A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.
The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With .after() , the content to be inserted comes from the method’s argument: $(target).after(contentToBeInserted) . With .insertAfter() , on the other hand, the content precedes the method and is inserted after the target, which in turn is passed as the .insertAfter() method’s argument: $(contentToBeInserted).insertAfter(target) .
div class="container">
h2>Greetings h2>
div class="inner">Hello div>
div class="inner">Goodbye div>
div>
Content can be created and then inserted after several elements at once:
Each inner element gets this new content:
div class="container">
h2>Greetings h2>
div class="inner">Hello div>
p>Test p>
div class="inner">Goodbye div>
p>Test p>
div>
An element in the DOM can also be selected and inserted after another element:
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved rather than cloned:
div class="container">
div class="inner">Hello div>
div class="inner">Goodbye div>
div>
h2>Greetings h2>
Important: If there is more than one target element, however, cloned copies of the inserted element will be created for each target except for the last one.
Passing a Function
As of jQuery 1.4, .after() supports passing a function that returns the elements to insert.
$( "p" ).after(function( )
return "
" + this.className + "";>);
This example inserts a after each paragraph, with each new containing the class name(s) of its preceding paragraph.
Additional Arguments
Similar to other content-adding methods such as .prepend() and .before() , .after() also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.
For example, the following will insert two new s and an existing after the first paragraph:
var $newdiv1 = $( "
newdiv2 = document.createElement( "div" ),
existingdiv1 = document.getElementById( "foo" );
$( "p" ).first().after( $newdiv1, [ newdiv2, existingdiv1 ] );
Since .after() can accept any number of additional arguments, the same result can be achieved by passing in the three s as three separate arguments, like so: $( "p" ).first().after( $newdiv1, newdiv2, existingdiv1 ) . The type and number of arguments will largely depend on the elements that are collected in the code.
Additional Notes:
- Prior to jQuery 1.9, .after() would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. The method might or might not have returned a new result depending on the number or connectedness of its arguments! As of jQuery 1.9, .after() , .before() , and .replaceWith() always return the original unmodified set. Attempting to use these methods on a node without a parent has no effect—that is, neither the set nor the nodes it contains are changed.
- By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, ). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.
Examples:
Inserts some HTML after all paragraphs.
Изменяем псевдоэлемент :after с помощью jQuery
Взаимодействовать с псевдоэлементами на странице не так просто, как с обычными HTML-элементами. До них невозможно «добраться» при помощи jQuery, а при необходимости изменить их содержимое приходиться делать различные трюки. Недавно мне понадобилось изменить фон псевдоэлемента :after . Сейчас я поделюсь с вами информацией о том, как это можно сделать.
У нас есть страничка с одним HTML-элементом (для наглядности) - заголовком h1. Внутри него находится ссылка.
h1 < color:#f2b940; font-size:1.5em; font-family: Verdana, sans-serif; margin:10px 0 0 10px; cursor: pointer; >.test < border-bottom: 1px dotted #323694; color: #323694; cursor: pointer; font-weight: normal; position: relative; text-decoration: none; >.test:afterLorem ipsum dolor sit amet, consectetur adipiscing elit
При клике на ссылку под этим HTML-элемент должен появляться всплывающий блок с содержимым. Справа от ссылки находится маленькое изображение стрелочки, указывающей вниз. После клика и появления всплывающего блока, эта стрелочка должна менять свое направление вверх.
Изображение стрелочки является фоном псевдоэлемента :after ссылки. Как же сделать так, чтобы все работало, как я описал?
Если добавить следующий код, то это НЕ СРАБОТАЕТ.
$('a.test:after').css('background', 'url(arrow.png) no-repeat 0 -50px');Дело в том, что пседоэлементы находятся вне DOM-дерева и к ним нельзя обратиться как к простым HTML-элементам, например, заголовками или абзацам. На самом деле решение есть и оно несложное. Нужно просто создать еще один CSS-класс и добавить в него правила, описывающие внешний вид измененного псевдоэлемента. В данном случае они будут следующими.
.test, .test2 < border-bottom: 1px dotted #323694; color: #323694; cursor: pointer; font-weight: normal; position: relative; text-decoration: none; >.test:after, .test2:after < background: url("arrow-blue.png") no-repeat; background-position: 100% -10px; content: ""; display: block; height: 5px; position: absolute; right: -17px; top: 50%; width: 10px; >.test2:after
Как вы видите, я просто добавил еще один CSS-класс к существующим правилам и создал еще одно правило для изменения позиции фона, чтобы наша стрелочка указывала вверх.
Последний штрих: пара строчек jQuery и задача рещена.
Вот таким образом можно изменять внешний вид псевдоэлементов на веб-страницах.
How to Select and Manipulate CSS pseudo-elements using jQuery
To select and manipulate CSS pseudo elements such as ::before and ::after, you can use the hover() method in a way that will prevent the “other text” from showing up. Firstly, pass the content to the pseudo element with a data attribute and then use jQuery to manipulate it:
$('span').hover(function () < $(this).addClass('change').attr('data-content', 'come'); >);
span: after < content: attr(data - content) 'other text'; >
html> html> head> title>Title of the Document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> style> span.change:after < content: attr(data-content) ' to W3Docs!'; > style> head> body> p>Hover over Wel p> span>Wel span> script> $(document).ready(function( ) < $('span').hover(function( ) < $(this).addClass('change').attr('data-content', 'come'); >); >); script> body> html>
The attr() Function
The attr() CSS function may be used with any CSS property, but the support for the properties other than content is experimental. The attr() function is used to get the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements and returns the value of the attribute on the originating element of pseudo-element.
The hover() Method
The hover() method specifies two functions to run when the mouse pointer hovers over the selected elements. It binds handlers for both the mouseenter and mouseleave events. If only one function is defined, it will be run for both the mouseenter and mouseleave events.