Get div from html jquery

Get div from html jquery

Description: Retrieve one of the elements matched by the jQuery object.

version added: 1.0 .get( index )

The .get() method grants access to the DOM nodes underlying each jQuery object. If the value of index is out of bounds — less than the negative number of elements or equal to or greater than the number of elements — it returns undefined . Consider a simple unordered list:

ul>
li id="foo">foo li>
li id="bar">bar li>
ul>

With an index specified, .get( index ) retrieves a single element:

Since the index is zero-based, the first list item is returned:

Each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get at the list item instead:

However, this syntax lacks some of the additional capabilities of .get(), such as specifying a negative index:

A negative index is counted from the end of the matched set, so this example returns the last item in the list:

Example:

Display the tag name of the click element.

html>
html lang="en">
head>
meta charset="utf-8">
title>get demo title>
style>
span
color: red;
>
div
background: yellow;
>
style>
script src="https://code.jquery.com/jquery-3.7.0.js"> script>
head>
body>
span>  span>
p>In this paragraph is an span>important span> section p>
div>input type="text"> div>
script>
$( "*", document.body ).on( "click", function( event )
event.stopPropagation();
var domElement = $( this ).get( 0 );
$( "span" ).first().text( "Clicked on - " + domElement.nodeName );
>);
script>
body>
html>

Demo:

.get() Returns: Array

Description: Retrieve the elements matched by the jQuery object.

version added: 1.0 .get()

Consider a simple unordered list:

ul>
li id="foo">foo li>
li id="bar">bar li>
ul>

Without a parameter, .get() returns an array of all of the elements:

All of the matched DOM nodes are returned by this call, contained in a standard array:

Example:

Select all divs in the document and return the DOM Elements as an Array; then use the built-in reverse() method to reverse that array.

Источник

jQuery - Get Content and Attributes

jQuery contains powerful methods for changing and manipulating HTML elements and attributes.

jQuery DOM Manipulation

One very important part of jQuery is the possibility to manipulate the DOM.

jQuery comes with a bunch of DOM related methods that make it easy to access and manipulate elements and attributes.

DOM = Document Object Model

The DOM defines a standard for accessing HTML and XML documents:

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."

Get Content - text(), html(), and val()

Three simple, but useful, jQuery methods for DOM manipulation are:

  • text() - Sets or returns the text content of selected elements
  • html() - Sets or returns the content of selected elements (including HTML markup)
  • val() - Sets or returns the value of form fields

The following example demonstrates how to get content with the jQuery text() and html() methods:

Example

The following example demonstrates how to get the value of an input field with the jQuery val() method:

Example

Get Attributes - attr()

The jQuery attr() method is used to get attribute values.

The following example demonstrates how to get the value of the href attribute in a link:

Example

The next chapter explains how to set (change) content and attribute values.

jQuery Exercises

jQuery HTML Reference

For a complete overview of all jQuery HTML methods, please go to our jQuery HTML/CSS Reference.

Источник

.html()

Мы можем использовать метод .html() для получения содержимого элемента. Если под селектор попадут несколько элементов, то будет извлечён только первый:

Данные будут извлечены из первого с искомым классом :

Данный метод использует нативное свойство innerHTML. Некоторые браузеры могут возвратить результат не совсем в таком виде, в котором он присутствует на странице. К примеру, Internet Explorer иногда упускает кавычки у значений атрибутов.

Пример:

Преобразуем html в текст, при клике по параграфу.

    p < margin:8px; font-size:20px; color:blue; cursor:pointer; >b < text-decoration:underline; >button    

Click to change the html

to a text node.

This does nothing.

Метод .html() может использоваться так же для замещения содержимого элемента.

Возьмём следующий HTML фрагмент:

Контент элемента может быть задан следующим образом:

$('div.demo-container') .html('

All new content. You bet!

');

Данная строчка заменит содержимое элемента :

Начиная с jQuery 1.4, метод .html() позволяет формировать HTML контент элемента в отдельной функции.

$('div.demo-container').html(function() < var emph = '' + $('p').length + ' paragraphs!'; return '

All new content for ' + emph + '

'; >);

Дан документ с шестью параграфами. Заменим их содержимое с на

All new content for 6 paragraphs!

.

Примеры

Пример: добавляем html каждому из div-ов

    .red   Hello    

Пример: добавляем html каждому из , а затем сразу же дополняем его содержимое.

    div       

Связанные уроки:

15 особенностей jQuery 1.4

jQuery постоянно развивается. Релиз версии 1.4 состоялся в январе. jQuery 1.4 получила много новых функций, расширений и имеет значительно лучшую производительность. Данная статья посвящена описанию основных улучшений jQuery 1.4.

Доступ к элементам контента с помощью jQuery

jQuery даёт возможность работать с элементами HTML и их содержимым различными способами. Например, вы можете добавить новые элементы внутрь, вокруг, до и после существующих элементов; вы можете заменить один элемент другим (или другими); вы можете читать и заменять содержимое элементов.

Шпаргалка jQuery:

  • Ajax
    • Global Ajax Event Handlers
      • .ajaxComplete()
        • :button
        • :checkbox
        • :checked
        • :disabled
        • :enabled
        • :file
        • :focus
        • :image
        • .serializeArray()
        • .serialize()
        • jQuery.param()
        • jQuery.ajax()
        • jQuery.ajaxSetup()
        • jQuery.ajaxPrefilter()
        • jQuery.ajaxTransport()
        • jQuery.get()
        • jQuery.post()
        • .load()
        • jQuery.getJSON()
        • jQuery.getScript()
        • .serialize()
        • .serializeArray()
        • jQuery.param()
        • .val()
        • .blur()
        • .change()
        • .focus()
        • .addClass()
        • .hasClass()
        • .removeClass()
        • .toggleClass()
        • .html()
        • .removeAttr()
        • .prop()
        • .removeProp()
        • .attr()
        • .val()
        • Collection Manipulation
          • jQuery.param()
          • .data()
          • .removeData()
          • Class Attribute
            • .addClass()
            • .hasClass()
            • .removeClass()
            • .toggleClass()
            • .clone()
            • .wrap()
            • .wrapAll()
            • .wrapInner()
            • .unwrap()
            • .append()
            • .appendTo()
            • .html()
            • .text()
            • .prepend()
            • .prependTo()
            • .after()
            • .before()
            • .insertAfter()
            • .insertBefore()
            • .unwrap()
            • .remove()
            • .empty()
            • .detach()
            • .replaceAll()
            • .replaceWith()
            • .removeProp()
            • .removeAttr()
            • .prop()
            • .attr()
            • .val()
            • .css()
            • .height()
            • .width()
            • .innerHeight()
            • .innerWidth()
            • .outerHeight()
            • .outerWidth()
            • .offset()
            • .position()
            • .scrollLeft()
            • .scrollTop()
            • .height()
            • .width()
            • .innerHeight()
            • .innerWidth()
            • .outerHeight()
            • .outerWidth()
            • jQuery.holdReady()
            • jQuery()
            • jQuery.noConflict()
            • jQuery.when()
            • .addClass()
            • .hasClass()
            • .removeClass()
            • .toggleClass()
            • .css()
            • .height()
            • .width()
            • .innerHeight()
            • .innerWidth()
            • .outerHeight()
            • .outerWidth()
            • .offset()
            • .position()
            • .scrollLeft()
            • .scrollTop()
            • .clearQueue()
            • .dequeue()
            • .data()
            • jQuery.hasData()
            • jQuery.removeData()
            • jQuery.dequeue()
            • .removeData()
            • jQuery.data()
            • .queue()
Оцените статью