如何使用JavaScript按标题选择元素并进行更新 [英] How to select an element by title with JavaScript and update it

查看:143
本文介绍了如何使用JavaScript按标题选择元素并进行更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过标题选择和修改元素?

How do you select and modify an element by it's title?

javascript: (function () {
  document.body.innerHTML += `<style>* {
    background:% 20#000 % 20!important;
    color:% 20#0f0 % 20!important;
    outline:% 20solid % 20#f00 % 201px % 20!important;
  } </style > `;
})();

我需要更新代码段/书签,以便在运行它(将其保存在书签栏上)时,它会更改文档中某个元素的位置.

I need to update the snippet / bookmarklet so when I run it (I have it on my bookmarks bar) it changes the position of a certain element in the document.

我唯一可以选择此元素的方法是通过其title属性.

The only way I could select this element is by its title attribute.

推荐答案

CSS选择器

使用选择器表示法通过其属性查找节点

Use the selector notation for finding a node by it's attribute

[title="element title attribute value"]


使用 JavaScript


Using JavaScript

与CSS中的选择器相同,但是您可以使用Node . querySelector"rel =" noreferrer> document.querySelector ,或者如果期望多个 Nodes ,则通过

Same selector as in CSS, but you can get the Node using document.querySelector, or if expecting multiple Nodes, a NodeList via document.querySelectorAll

var node = document.querySelector('[title="element title attribute value"]');


当您执行.innerHTML时,将导致在调用它的节点中重新解析所有 HTML ,这实际上可能会破坏网页的各个部分.您应该使用 DOM方法创建节点.例如


When you do .innerHTML, you are causing a re-parse of all HTML in the node you've called it on and this can literally destroy sections of web pages. You should use DOM methods for creating nodes, instead. e.g.

var style = document.createElement('style');
style.appendChild(document.createTextNode('div {border: 1px solid red}'));
document.body.appendChild(style);


JavaScript 转换为小书签很简单


Converting JavaScript into a bookmarklet is as simple as

bookmarklet = 'javascript:'
    + encodeURIComponent('(function () {' + code + '}())')
    + ';';

> 这里是一个小提琴 ,您可以在其中粘贴代码

Here is a fiddle where you can just paste in code

这篇关于如何使用JavaScript按标题选择元素并进行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆